mutliple search and replace
Carel Fellinger
cfelling at iae.nl
Thu Mar 28 17:48:37 EST 2002
Trung Hoang <thoa0025 at mail.usyd.edu.au> wrote:
> hey Gustavo,
> actually i wished to do the replacement in one sweep and occuring in any
> order.. to avoid problems.. is it easy?
yes it is, use re.sub and remember the repl param to re.sub can be any
Python callable too, like:
>>> import re
>>> def OneSweep(replacements, txt):
... def repl(match):
... return replacements[match.group()]
... matching = "|".join([re.escape(x) for x in replacements])
... return re.sub(matching, repl, txt)
...
>>> txt = "SPAM and eggs or spam and EGGS"
>>> print OnesWeep({"SPAM": "spam", "spam": "SPAM"}, txt)
spam and eggs or SPAM and EGGS
--
groetjes, carel
More information about the Python-list
mailing list