Help, Search and Substitute

Greg Jorgensen gregj at
Sat Nov 4 10:22:23 CET 2000

> "Pete Shinners" <pete at> wrote in message
> news:8tcp98$t79$1 at
> > 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 just wrote something similar to do bulk mailings from templates and merge
files. My first version used re.sub but was too slow, but this technique is
fast enough:

# break the template into list of chunks that are either plain text or
rx = re.compile(r'(\{[a-zA-Z0-9_]+\})')
chunks = rx.split(template)

# values dict contains field_name: value entries, i.e.
values = {'NAME':'Greg', 'PHONE':'503-555-1212', ....}

# look at each chunk and change {field_name} to merged value
message = []
for s in chunks:
    if s and s[0] == '{' and s[-1] == '}':    # {field_name}
        s = s[1:-1]    # strip surrounding {...}
        s = values.get(s, s)    # get value of field_name, or field_name if
not in merge dict


# put merged message back together
''.join(message)        # bizarre join syntax

print message

My complete mailmerge program handles nested {...} and will recursively
process the message until all {FIELDS} are replaced; this allows {...} to
appear in the merge file as well as the template.

Greg Jorgensen
Deschooling Society
Portland, Oregon, USA
gregj at

More information about the Python-list mailing list