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 stringYou can also pass the substitute method a dictionary with key/value pairs for your template:
>>> thisTmp = string.Template("The $speed $color $thing1")
>>> thisTmp.substitute(speed='quick', color='brown', thing1='fox')
'The quick brown fox'
>>> 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.
3 comments:
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!
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'})
'FOO_BLAH'
You can also override the delimiters if that's more convenient. $ and {} are just the defaults.
Many thanks for such a quick response. That is right what I was looking for. Sorry if my question was somewhat messy 8)
Post a Comment