Help, Search and Substitute

Fredrik Lundh fredrik at
Thu Nov 2 23:09:58 CET 2000

Pete Shinners wrote:
> I've got to write a search and replace type routine that
> works on a template file. i have a dictionary with string
> keys and values. i want parse a template file and replace
> "{KEYNAME}" with the value of KEYNAME from my dictionary.
> i'm guessing this is where the reg-exp's come in to play?
> i assume it's time i sit down and get the basics on these?

# based on
# from (the eff-bot guide to) The Python Standard Library

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, "{foo}fie{bar}")


More information about the Python-list mailing list