python - 检查转义字符的 python 字符串

标签 python html 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)

有更好的方法吗?

最佳答案

您可以使用 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/

相关文章:

python - 找到具有 k 个唯一字母的最大可能子串。 (递归)

Python逆幂集生成器

html - 如何更改元素的不透明度/透明度并保持主体背景图像仍然可见?

javascript - 使 div 跟随文本区域中的插入符号位置?

java - 如何在没有正则表达式的情况下解析字符串

python - Pandas 测量条件为真时耗时

python - 如何在 python 中的 OpenCv 中添加自定义 Keras 模型

javascript - addChild 给出错误,JavaScript

java - 在 Java 中使用递归反转字符串

string - 定期拆分字符串