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

标签 python string escaping

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/

相关文章:

python - 属性错误 : 'RegexURLResolver' object has no attribute '_urlconf_module'

python - 用于多类分类的 SVM(一对多)置信度估计

python - 切片、合并会计年度日期并将其映射到日历年日期到新列

string - 比较 Fortran 中的两个字符串

java - 方法不更新原始字符串变量

c# - 当设置另有说明时,为什么 XmlReader 会检查非法字符?

python - 如何将Python2中的所有: print "string",替换为Python3中的: print ("string"),?

C 解密程序 - 检测到堆损坏

ssh - 如何通过 ssh 命令转义 sed 中的 $?

php - 转义 SED 命令