PEP 750
lastmod 2025-04-11created 2025-04-111 edits
Template Strings
About
- PEP 750 introduces a new string literal to Python: template strings (t"...")
- A generalized form of f-strings that creates a Template type, letting you process the strings and interpolated values before they are combined
- Useful for web templates, security checks, DSLs (Domain-Specific Languages), and more
Relationship to other PEPs
- f-strings were introduced in PEP 498, and their syntax was extended in PEP 701
- PEP 501 proposed general template strings (i-strings), but was deferred
- The current PEP 750 is a simplified and generalized form of PEP 501, developed from the earlier ideas
Motivation and need
- f-strings are simple, but interpolated values cannot be processed beforehand, which can cause security problems
- Risk of security vulnerabilities such as SQL injection and XSS attacks
- With template strings, interpolated values can be processed beforehand and used safely
Example:
evil = "<script>alert('evil')</script>"
template = t"<p>{evil}</p>"
assert html(template) == "<p><script>alert('evil')</script></p>"
Template string specification
Template string literals
- Defined with the prefix t or T
- Evaluates to the string.templatelib.Template type
- Supports syntax similar to f-strings, nesting is also possible
- Can be combined with the r prefix (rt, tr)
- Cannot be combined with the u or b prefixes
- f-strings and template strings cannot be mixed
Template type
- An immutable type with the following attributes:
- strings: a tuple of string pieces
- interpolations: a tuple of interpolation objects
- values: a tuple of the interpolated values
- iter(): an iterator that returns the strings and interpolations in order
Interpolation type
- value: the evaluated result
- expression: the original interpolation expression string
- conversion: the conversion type (r, s, a, or None)
- format_spec: the format string
See also
Favorite site
- PEP 750 – Template Strings | peps.python.org
- PEP 750 – Template strings (t-strings) accepted | GeekNews
Pages that link here