New in version 2.4.
Templates provide simpler string substitutions as described in PEP 292. Instead of the normal %
-based substitutions, Templates support $
-based substitutions, using the following rules:
$$
is an escape; 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"
.
Any other appearance of $
in the string will result in a ValueError
being raised.
The string
module provides a Template
class that implements these rules. The methods of Template
are:
-
class
-
The constructor takes a single argument which is the template string.
-
Performs the template substitution, returning a new string. mapping is any dictionary-like object with keys that match the placeholders in the template. Alternatively, you can provide keyword arguments, where the keywords are the placeholders. When both mapping and kws are given and there are duplicates, the placeholders from kws take precedence.
substitute
( mapping [, **kws ] )-
Like
substitute()
, except that if placeholders are missing from mapping and kws, instead of raising aKeyError
exception, the original placeholder will appear in the resulting string intact. Also, unlike withsubstitute()
, any other appearances of the$
will simply return$
instead of raisingValueError
.While other exceptions may still occur, this method is called “safe” because substitutions always tries to return a usable string instead of raising an exception. In another sense,
safe_substitute()
may be anything other than safe, since it will silently ignore malformed templates containing dangling delimiters, unmatched braces, or placeholders that are not valid Python identifiers.
safe_substitute
( mapping [, **kws ] )Template
instances also provide one public data attribute:-
This is the object passed to the constructor’s template argument. In general, you shouldn’t change it, but read-only access is not enforced.
template
-
string.
Template
(
template
)
Here is an example of how to use a Template:
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
...
ValueError: Invalid placeholder in string: line 1, col 11
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'