4.1.2 Template strings

Templates are Unicode strings that can be used to provide string substitutions as described in PEP 292. There is a Template class that is a subclass of unicode, overriding the default __mod__() method. Instead of the normal "%"-based substitutions, Template strings support "$"-based substitutions, using the following rules:

Any other appearance of "$" in the string will result in a ValueError being raised.

Template strings are used just like normal strings, in that the modulus operator is used to interpolate a dictionary of values into a Template string, e.g.:

>>> from string import Template
>>> s = Template('$who likes $what')
>>> print s % dict(who='tim', what='kung pao')
tim likes kung pao
>>> Template('Give $who $100') % dict(who='tim')
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder at index 10

There is also a SafeTemplate class, derived from Template which acts the same as Template, except that if placeholders are missing in the interpolation dictionary, no KeyError will be raised. Instead the original placeholder (with or without the braces, as appropriate) will be used:

>>> from string import SafeTemplate
>>> s = SafeTemplate('$who likes $what for ${meal}')
>>> print s % dict(who='tim')
tim likes $what for ${meal}

The values in the mapping will automatically be converted to Unicode strings, using the built-in unicode() function, which will be called without optional arguments encoding or errors.

Advanced usage: you can derive subclasses of Template or SafeTemplate to use application-specific placeholder rules. To do this, you override the class attribute pattern; the value must be a compiled 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.