Python idiom: Multiple search-and-replace

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

Randall Hopper <aa8vb at> 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

import re
import string

symbol_map = { "foo": "FOO", "bar": "BAR" }

def symbol_replace(match, get=symbol_map.get):
    return get(, "")

symbol_pattern = re.compile(
    "(" + string.join(map(re.escape, symbol_map.keys()), "|") + ")"

print symbol_pattern.sub(symbol_replace, "foobarfiebarfoo")



<!-- (the eff-bot guide to) the standard python library:

More information about the Python-list mailing list