Python idiom: Multiple search-and-replace

Fredrik Lundh effbot at telia.com
Wed Apr 12 10:19:45 EDT 2000


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