>> import -6ren">
gpt4 book ai didi

python - 转义 Python 字符串中的特殊字符

转载 作者:IT老高 更新时间:2023-10-28 21:06:49 30 4
gpt4 key购买 nike

Python 是否有一个函数可以用来转义字符串中的特殊字符?

例如,I'm "stuck":\ 应该变成 I\'m\"stuck\":\\

最佳答案

使用 re.escape

>>> import re
>>> re.escape(r'\ a.*$')
'\\\\\\ a\\.\\*\\$'
>>> print(re.escape(r'\ a.*$'))
\\\ a\.\*\$
>>> re.escape('www.stackoverflow.com')
'www\\.stackoverflow\\.com'
>>> print(re.escape('www.stackoverflow.com'))
www\.stackoverflow\.com

在此重复:

re.escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

从 Python 3.7 开始,re.escape() 已更改为仅转义对正则表达式操作有意义的字符。

关于python - 转义 Python 字符串中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4202538/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com