And*_*rew 5 html python string html-escape-characters
我正在尝试检查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)
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?
>>> 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'
Run Code Online (Sandbox Code Playgroud)
&,;匹配&,;字面意思.\w匹配单词字符(字母,数字,_).\w+ 匹配一个或多个单词字符.