all Python 3stringterm
string.Template
templates
A string template with $var or ${var} substitution. Safer than % and format() for user input. Its methods: substitute(), safe_substitute().
Syntax
string.Template(template)
t.substitute(mapping={}, /, **kwds)
t.safe_substitute(mapping={}, /, **kwds)
The "safer" part is literal: a Template supports neither attribute access nor indexing, so a user-supplied template cannot reach into an object's internals the way {0.__class__.__mro__} can with str.format(). Mind the dollar sign — a literal $ must be doubled as $$, otherwise substitute() raises ValueError on something like '$5'. And safe_substitute() validates nothing at all: a typo such as $nmae is left in the output as plain text instead of raising KeyError, which is convenient for drafts but hides real mistakes.
Examples
import string
t = string.Template('Hello, $name!')
print(t.substitute(name='Alice')) # → Hello, Alice!
t2 = string.Template('${item} costs $price USD')
print(t2.substitute(item='apple', price=1.5)) # → apple costs 1.5 USD
print(t2.safe_substitute(item='apple')) # → apple costs $price USD
t3 = string.Template('Dear $who, thank you.')
print(t3.substitute({'who': 'Bob'})) # → Dear Bob, thank you.
See also
Open in the full glossarydocs.python.orgReport an inaccuracy