我正在尝试检查 python 中的字符串是否包含转义字符。最简单的方法是设置转义字符列表,然后检查列表中的任何元素是否在字符串中:
s = "A & B"
escaped_chars = ["&",
""",
"'",
">"]
for char in escaped_chars:
if char in s:
print "escape char '{0}' found in string '{1}'".format(char, s)
有更好的方法吗?
最佳答案
您可以使用 regular expression (另见 re
module documentation ):
>>> s = "A & B"
>>> import re
>>> matched = re.search(r'&\w+;', s)
>>> if matched:
... print "escape char '{0}' found in string '{1}'".format(matched.group(), s)
...
escape char '&' found in string 'A & B'
&
,;
按字面意思匹配&
,;
。\w
匹配单词字符(字母、数字、_
)。\w+
匹配一个或多个单词字符。
关于python - 检查转义字符的 python 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31738515/