Help, Search and Substitute

Fredrik Lundh fredrik at effbot.org
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 re-example-5.py
# from (the eff-bot guide to) The Python Standard Library
# http://www.pythonware.com/people/fredrik/librarybook.htm

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

</F>





More information about the Python-list mailing list