4.1.2 Template strings

Templates provide simpler string substitutions as described in PEP 292. Instead of the normal "%"-based substitutions, Templates support "$"-based substitutions, using the following rules:

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:

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:

See About this document... for information on suggesting changes.