Используйте re.sub
:
replacements = {'the':'a',
'this':'that'}
def replace(match):
return replacements[match.group(0)]
# notice that the 'this' in 'thistle' is not matched
print re.sub('|'.join(r'\b%s\b' % re.escape(s) for s in replacements),
replace, 'the cat has this thistle.')
Отпечатки
a cat has that thistle.
Примечания:
re.escape
, чтобы избежать интерпретации их как регулярных выражений. r'\b'
, чтобы убедиться, что совпадения предназначены только для целых слов.