The alternate substitution delimiter introduced in 2.4 (string.Template) was supposed to make string substitution easier. In fact it is a little cumbersome to use. This recipe employs a little stack hackery to make it as easy as it ought to be.
1 2 3 4 5 6 7 8 9 10 11 12 13
# Auto-prints a string using the new (as of 2.4) string-template # based substitution. import copy, inspect from string import Template def printfmt(template): frame = inspect.stack() try: var = copy.copy(frame.f_globals) var.update(frame.f_locals) print Template(template).safe_substitute(var) finally: del frame
This hides having to create the Template object and call substitute/safe_substitute on it. For example:
num = 10 word = "spam"
printfmt("I would like to order $num units of $word, please")
I would like to order 10 units of spam, please