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

JTF*_*ier 3 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()
Run Code Online (Sandbox Code Playgroud)

mkr*_*er1 9

将搜索/替换字符串存储在列表中并循环遍历它:

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

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

stuff = stuff.capitalize()
Run Code Online (Sandbox Code Playgroud)

  • 我假设它已经被定义过,就像在原始代码中一样. (3认同)