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/