This question already has answers here:

How to replace multiple substrings of a string?
(21个答案)
我想对一个字符串进行多次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/

10-16 22:55