更新时间:2023-02-17 21:30:19
import re
def multiple_replace(dict, text):
# Create a regular expression from the dictionary keys
regex = re.compile(r'(%s)' % "|".join(dict.keys()))
return regex.sub(lambda mo: dict[
[ k for k in dict if
re.search(k, mo.string[mo.start():mo.end()])
][0]], text)
d = { r'ba[rz]*' : 'bar', '<' : '[' }
s = 'barzzzzzz <'
print multiple_replace(d, s)
给予:
bar [