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.
New in version 2.4.
The string module provides a Template class that implements
these rules. The methods of Template are:
class Template( |
template) |
-
The constructor takes a single argument which is the template string.
substitute( |
mapping[, **kws]) |
-
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.
safe_substitute( |
mapping[, **kws]) |
-
Like substitute(), except that if placeholders are missing from
mapping and kws, instead of raising a KeyError
exception, the original placeholder will appear in the resulting string
intact. Also, unlike with substitute(), any other appearances of the
"$" will simply return "$" instead of raising
ValueError.
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.
Template instances also provide one public data attribute:
- template
-
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.
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 10
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
Advanced usage: you can derive subclasses of Template to customize the
placeholder syntax, delimiter character, or the entire regular expression used
to parse template strings. To do this, you can override these class
attributes:
- delimiter - This is the literal string describing a placeholder
introducing delimiter. The default value "$". Note that this
should not be a regular expression, as the implementation will
call re.escape() on this string as needed.
- idpattern - This is the regular expression describing the pattern
for non-braced placeholders (the braces will be added automatically as
appropriate). The default value is the regular expression
"[_a-z][_a-z0-9]*".
Alternatively, you can provide the entire regular expression pattern by
overriding the class attribute pattern. If you do this, the value must
be a regular expression object with four named capturing groups. The
capturing groups correspond to the rules given above, along with the invalid
placeholder rule:
- escaped - This group matches the escape sequence,
e.g. "$$", in the default pattern.
- named - This group matches the unbraced placeholder name; it
should not include the delimiter in capturing group.
- braced - This group matches the brace enclosed placeholder name;
it should not include either the delimiter or braces in the capturing
group.
- invalid - This group matches any other delimiter pattern (usually
a single delimiter), and it should appear last in the regular
expression.
Release 2.5.4, documentation updated on 23rd December, 2008.
See About this document... for information on suggesting changes.