Aside from the string constants and the deprecated string functions
(moved to string methods), Python's string module also includes string
templates. The template itself is a class which receives a string as
its argument. The object instantiated from that class is called a
template string object. Template strings were first introduce in
Python 2.4.
Where string-formatting operators used the percentage sign ('%') for
substitutions, the Template object uses dollar signs ('$'):
- "$$" is an escape sequence; it is replaced with a single "$".
- "$<identifier>" names a substitution placeholder matching a
mapping key of "<identifier>". By default, "<identifier>" must spell
a Python identifier. The first non-identifier character after the "$"
character terminates this placeholder specification.
- "${<identifier>}" is equivalent to "$<identifier>". It is required
when valid identifier characters follow the placeholder but are not
part of the placeholder, such as "${noun}ification".
Outside of these uses of the dollar sign, any appearance of '$' will
cause a ValueError to be raised.
The methods available through template strings are as follows:
- class Template(template): The constructor takes a single argument which is the template string.
- substitute(mapping[, **keywords]): Method
that substitutes the string values (mapping for the template
string values. mapping is a dictionary, and its values may be
accessed as a dictionary. If the keywords argument is used, it
represents placeholders. Where both mapping and
keywords are used, the latter takes precedence. If a
placeholder is missing from mapping or keywords, a
KeyError is thrown.
- safe_substitute(mapping[, **keywords]):
Functions similarly to substitute() (above). However, if a
placeholder is missing from mapping or keywords, the
original placeholder will be used by default, thus avoiding the
KeyError. Also, any occurrence of '$' will return a dollar sign.
Template objects also have one publicly available attribute.
template is the object passed to the constructor's
template argument. While read-only access is not enforced, it
is best not to change this attribute in your program.
The sample shell session below serves to illustrate template string
objects.
>>> from string import Template
>>> s = Template('$when, $who $action $what.')
>>> s.substitute(when='In the summer', who='John', action='drinks', what='iced tea')
'In the summer, John drinks iced tea.'
>>> s.substitute(when='At night', who='Jean', action='eats', what='popcorn')
'At night, Jean eats popcorn.'
>>> s.template
'$when, $who $action $what.'
>>> d = dict(when='in the summer')
>>> Template('$who $action $what $when').safe_substitute(d)
'$who $action $what in the summer'