转义 Python 字符串中的特殊字符 [英] Escape special characters in a Python string

查看:107
本文介绍了转义 Python 字符串中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如,我卡住了";:\ 应该变成 I\'m \"stuck\";:\\.

解决方案

使用 re.escape

<预><代码>>>>进口重新>>>re.escape(r'\ a.*$')'\\\\\\ a\\.\\*\\$'>>>打印(重新转义(r'\ a.*$'))\\\ a\.\*\$>>>re.escape('www.stackoverflow.com')'www\\.stackoverflow\\.com'>>>打印(重新转义('www.stackoverflow.com'))www\.stackoverflow\.com

在此重复:

<块引用>

re.escape(string)

返回所有非字母数字反斜杠的字符串;如果您想匹配可能包含正则表达式元字符的任意文字字符串,这将非常有用.

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

Does Python have a function that I can use to escape special characters in a string?

For example, I'm "stuck" :\ should become I\'m \"stuck\" :\\.

解决方案

Use 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

Repeating it here:

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.

As of Python 3.7 re.escape() was changed to escape only characters which are meaningful to regex operations.

这篇关于转义 Python 字符串中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆