python - 如何在 Python 中链接多个 re.sub() 命令

标签 python regex

<分区>

我想对一个字符串进行多次 re.sub() 替换,并且每次都用不同 字符串进行替换。

当我有很多子字符串要替换时,这看起来很重复。有人可以建议一个更好的方法吗?

stuff = re.sub('__this__', 'something', stuff)
stuff = re.sub('__This__', 'when', stuff)
stuff = re.sub(' ', 'this', stuff)
stuff = re.sub('.', 'is', stuff)
stuff = re.sub('__', 'different', stuff).capitalize()

最佳答案

将搜索/替换字符串存储在列表中并对其进行循环:

replacements = [
    ('__this__', 'something'),
    ('__This__', 'when'),
    (' ', 'this'),
    ('.', 'is'),
    ('__', 'different')
]

for old, new in replacements:
    stuff = re.sub(old, new, stuff)

stuff = stuff.capitalize()

请注意,当您想要替换文字 . 字符时,您必须使用 '\.' 而不是 '.'.

关于python - 如何在 Python 中链接多个 re.sub() 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46328547/

相关文章:

python - 如何从 OpenCV 3.1 中的文件加载 SVM 数据?

python - 如何添加默认路径以在其中查找 python 脚本文件?

python - 使用正则表达式获取所需行的问题

regex - matchstr 与 vimscript 中的正则表达式不匹配

python - 如何编写 __iter__ 从叶节点迭代回根?

python - 如何卸载损坏的 pip

php - 查找以非字母符号开头的行

c - 匹配不在引号内的模式

javascript - 如何在javascript中组合正则表达式?

python - scikit-learn (sklearn) 中 GaussianMixture 的负 BIC 值