ASPN ActiveState Programmer Network
  ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups | Web Services
SEARCH
advanced | search help

Reference
ActivePython 2.4
What's New
What's new in Python 2.4?
Contents
1 PEP 218: Built-In Set Objects
2 PEP 237: Unifying Long Integers and Integers
3 PEP 289: Generator Expressions
4 PEP 292: Simpler String Substitutions
5 PEP 318: Decorators for Functions and Methods
6 PEP 322: Reverse Iteration
7 PEP 324: New subprocess Module
8 PEP 327: Decimal Data Type
9 PEP 328: Multi-line Imports
10 PEP 331: Locale-Independent Float/String Conversions
11 Other Language Changes
12 New, Improved, and Deprecated Modules
13 Build and C API Changes
14 Porting to Python 2.4
15 Acknowledgements
About this document ...

MyASPN >> Reference >> ActivePython 2.4 >> What's New >> What's new in Python 2.4?
ActivePython 2.4 documentation

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.

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState 2004 All rights reserved