mutliple search and replace
Gustavo Cordova
gcordova at hebmex.com
Thu Mar 28 17:44:48 EST 2002
>
> hey Gustavo,
>
> actually i wished to do the replacement in one sweep and
> occuring in any
> order.. to avoid problems.. is it easy?
>
> cheers
>
Hmmm... it becomes a bit more complicated.
Say, you have this huge string:
>>> HugeString = """ ... lotsa text ..."""
And, your dictionary with search items and replacements:
>>> ReplacementsDict = { "find":"replace", ... }
So, you need to find *any* key, so you can use a regexp:
>>> import re
>>> rxFindKey = re.compile("|".join(ReplacementsDict.keys()), re.S)
To do all the replacements. just do a loop:
>>> match = rxFindKey.search(HugeString)
>>> while match:
... found = match.group(0)
... HugeString = HugeString.replace(found, ReplacementsDict[found])
... match = rxFindKey.search(HugeString)
So, after the loop, you've got all that done.
Good luck!
-gustavo
More information about the Python-list
mailing list