我想对字符串进行多次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()
答案 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)