4 PEP 292: Simpler String Substitutions

Some new classes in the standard library provide an alternative mechanism for substituting variables into strings; this style of substitution may be better for applications where untrained users need to edit templates.

The usual way of substituting variables by name is the % operator:

>>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
'2: The Best of Times'

When writing the template string, it can be easy to forget the "i" or "s" after the closing parenthesis. This isn't a big problem if the template is in a Python module, because you run the code, get an ``Unsupported format character'' ValueError, and fix the problem. However, consider an application such as Mailman where template strings or translations are being edited by users who aren't aware of the Python language. The format string's syntax is complicated to explain to such users, and if they make a mistake, it's difficult to provide helpful feedback to them.

PEP 292 adds a Template class to the string module that uses "$" to indicate a substitution. Template is a subclass of the built-in Unicode type, so the result is always a Unicode string:

>>> import string
>>> t = string.Template('$page: $title')
>>> t.substitute({'page':2, 'title': 'The Best of Times'})
u'2: The Best of Times'

If a key is missing from the dictionary, the substitute method will raise a KeyError. There's also a safe_substitute method that ignores missing keys:

>>> t = string.SafeTemplate('$page: $title')
>>> t.safe_substitute({'page':3})
u'3: $title'

See Also:

PEP 292, Simpler String Substitutions
Written and implemented by Barry Warsaw.

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