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

时间:2017-09-20 17:40:27

标签: 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()

2 个答案:

答案 0 :(得分:6)

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

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

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

stuff = stuff.capitalize()

答案 1 :(得分:-1)

tuple = (('__this__', 'something'),('__This__', 'when'),(' ', 'this'),('.', 'is'),('__', 'different'))

for element in tuple:
    stuff = re.sub(element[0], element[1], stuff)