检查Python字符串中的转义字符

5

我正在尝试检查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)

有更好的方法吗?


1
你为什么要寻求更好的方法?你现在的方法有什么问题吗?丑陋?性能不佳?请提出具体问题。 - Markus Meskanen
2
因为还有许多其他的转义字符我没有包括在内,例如 < 等。 - Andrew
1个回答

7
你可以使用正则表达式 (另请参阅 re模块文档):
>>> 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+ 匹配一个或多个单词字符。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接