multiple replacements
David Goodger
dgoodger at bigfoot.com
Tue Jun 27 23:11:45 EDT 2000
on 2000-06-27 08:47, siva1311 at my-deja.com (siva1311 at my-deja.com) wrote:
> I am a newbie Python programmer and was wondering the best way to make
> multiple replacements of text strings in a file.
Perhaps a bit complex for a newbie, but the most definitive answer I've seen
so far has been Fredrik Lundh's 2000-04-12 reply to the "Python idiom:
Multiple search-and-replace" thread:
=============== forward ================
Randall Hopper <aa8vb at yahoo.com> wrote:
> Is there a Python feature or standard library API that will get me less
> Python code spinning inside this loop? re.multisub or equivalent? :-)
haven't benchmarked it, but I suspect that this approach
is more efficient:
...
# based on re-example-5.py
import re
import string
symbol_map = { "foo": "FOO", "bar": "BAR" }
def symbol_replace(match, get=symbol_map.get):
return get(match.group(1), "")
symbol_pattern = re.compile(
"(" + string.join(map(re.escape, symbol_map.keys()), "|") + ")"
)
print symbol_pattern.sub(symbol_replace, "foobarfiebarfoo")
...
</F>
<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
More information about the Python-list
mailing list