Help, Search and Substitute

Carel Fellinger cfelling at iae.nl
Thu Nov 2 18:38:51 EST 2000


Pete Shinners <pete at visionart.com> 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?

Why use reg-exp's where simple substitutions will do?  Simply use the
dict you made and use the special %(name)s substitution trick, like:


$ cat template-file
This %(NOUN)s is %(ADJECTIVE)s!
This %(NOUN)s is
%(ADJECTIVE)s!

$ python
>>> template = open('template-file).read()
>>> template_dict = {"NOUN":"parrot", "ADJECTIVE":"dead"}
>>> print template % template_dict
This parrot is dead!
This parrot is
an dead too!




-- 
groetjes, carel



More information about the Python-list mailing list