Monday, May 26, 2008

Python String Templates

The Template class, found in the standard Python string module, is extremely useful. Start with a template string containing keys you want to replace. By default keys start with "$".

>>> import string
>>> thisTmp = string.Template("The $speed $color $thing1")
>>> thisTmp.substitute(speed='quick', color='brown', thing1='fox')
'The quick brown fox'
You can also pass the substitute method a dictionary with key/value pairs for your template:
>>> strDict = {'speed':'slow', 'color':'toupe', 'thing1':'mango'}
>>> thisTmp.substitute(strDict)
'The slow toupe mango'
This makes it easy to insert variable parts in an otherwise fixed string or file. I use it all the time for generating table-based HTML reports.

Create a file like "report.html" with string keys like "$rowValue1" or "$user" in the appropriate places, and have your script read in the contents as a string Template and do the substitutions. This also allows the report layout/appearance to be altered later without touching the script code.


Anonymous said...

thanks for the example, mate.
By the way do you know how to handle cases when one needs to substitute a substring? For instance:

"$foo_BLAH" with dictionary = ["foo" : "FOO"]

and I'd like to get "FOO_BLAH" as a result. How do you let the template know the terminal character for the name?

Thank you!

Adam Pletcher said...

If I understand you correctly, I think you can just add braces in the template string:

>>> s = string.Template('${foo}_BLAH')
>>> s.substitute({'foo': 'FOO'})

You can also override the delimiters if that's more convenient. $ and {} are just the defaults.

Anonymous said...

Many thanks for such a quick response. That is right what I was looking for. Sorry if my question was somewhat messy 8)

Pankaj Pandey said...

Python >2.6 strings support format method, which seems to perform similar function.


I guess this should work for most use cases you mention.