Template strings: t-strings
suggest changePython 3.14 added a new string prefix, t, defined in PEP 750. A t-string looks like an f-string, but it doesn't produce a str. It produces a string.templatelib.Template object. That object keeps the literal text and the values of the {...} expressions apart, so a function can decide how to combine them.
That's the whole idea: an f-string combines the parts right away, and a t-string gives the parts to your code. This matters whenever inserting a value as-is is a bug or a security hole:
- HTML, where
<script>in a user comment must be escaped - SQL, where a value must become a query parameter, not part of the query text
- shell commands, log messages with structured fields, translations
Examples were run with Python 3.14.4. t-strings are a syntax change, so code that uses them won't even parse on 3.13 and older.
Don't confuse t-strings with string.Template, the older $name substitution class from the string module (shown in Simple data output program using template). They solve different problems, compared at the end of this article.
f-string versus t-string
The same text with f and with t:
name = "Ada"
count = 3
f = f"Hello {name}, you have {count} new messages"
t = t"Hello {name}, you have {count} new messages"
print(type(f).__name__, f)
print(type(t).__name__)
print(t.strings)
print(t.values)
for item in t.interpolations:
print(item)
str Hello Ada, you have 3 new messages
Template
('Hello ', ', you have ', ' new messages')
('Ada', 3)
Interpolation('Ada', 'name', None, '')
Interpolation(3, 'count', None, '')
A Template has three read-only attributes:
strings: a tuple of the literal text piecesinterpolations: a tuple ofInterpolationobjects, one per{...}values: a shortcut for the.valueof each interpolation
The expressions are evaluated when the t-string is evaluated, exactly like in an f-string. What's missing is the final step that formats each value and joins everything into one string.
Interpolation objects
Each Interpolation records everything that was written inside the braces:
| Attribute | Meaning | For {price:.2f} |
|---|---|---|
value |
the evaluated result of the expression | 4.5 |
expression |
the source text of the expression | 'price' |
conversion |
'r', 's', 'a' or None |
None |
format_spec |
the text after : |
'.2f' |
Iterating over a Template yields its parts in order: str for literal text and Interpolation for each expression:
from string.templatelib import Interpolation
price = 4.5
item = "coffee"
t = t"{item!r} costs {price:.2f} EUR"
for part in t:
if isinstance(part, str):
print(f"str: {part!r}")
else:
print(f"expr: {part.expression!r} value={part.value!r} "
f"conversion={part.conversion!r} format_spec={part.format_spec!r}")
expr: 'item' value='coffee' conversion='r' format_spec=''
str: ' costs '
expr: 'price' value=4.5 conversion=None format_spec='.2f'
str: ' EUR'
The conversion and format spec are only recorded, not applied. value is still the original 'coffee' and 4.5. Applying them, or ignoring them, is up to the code that processes the template.
strings always has exactly one more element than interpolations, so the two tuples interleave: strings[0], interpolations[0], strings[1], and so on. To keep that true, empty strings are stored where two interpolations touch. Iteration skips the empty strings:
a, b = 1, 2
print(t"{a}{b}".strings)
print(list(t"{a}{b}"))
print(list(t"x{a}y"))
print(t"".strings, list(t""))
('', '', '')
[Interpolation(1, 'a', None, ''), Interpolation(2, 'b', None, '')]
['x', Interpolation(1, 'a', None, ''), 'y']
('',) []
Use strings and interpolations when you want to zip them by position, and iteration when you just want to walk the parts.
A Template is not a string
Template deliberately has no way to turn itself into the "obvious" string. str() and f-strings give you its repr, and you can't concatenate it with a str:
user = "Ada"
t = t"Hi {user}"
print(str(t))
print(f"{t}")
try:
t + "!"
except TypeError as e:
print("TypeError:", e)
print(t"Hi {user}" == t"Hi {user}")
Template(strings=('Hi ', ''), interpolations=(Interpolation('Ada', 'user', None, ''),))
Template(strings=('Hi ', ''), interpolations=(Interpolation('Ada', 'user', None, ''),))
TypeError: can only concatenate string.templatelib.Template (not "str") to string.templatelib.Template
False
This is on purpose. If str(t) produced the f-string result, it would be easy to skip the escaping step by accident. Two templates also don't compare equal even with the same content, because Template uses the default identity comparison.
Writing a render function
Any code that takes a Template and returns something is a template processor. The simplest one rebuilds what an f-string would have produced. string.templatelib.convert() applies a !r/!s/!a conversion, and the built-in format() applies a format spec:
from string.templatelib import Template, Interpolation, convert
def render(template: Template) -> str:
parts = []
for part in template:
match part:
case str() as s:
parts.append(s)
case Interpolation(value, _, conversion, format_spec):
value = convert(value, conversion)
parts.append(format(value, format_spec))
return "".join(parts)
name = "Ada"
balance = 1234.5
width = 12
print(render(t"{name!r:>8} owes {balance:{width},.2f} EUR"))
print(f"{name!r:>8} owes {balance:{width},.2f} EUR")
print(render(t"{balance = :.1f}"))
'Ada' owes 1,234.50 EUR
'Ada' owes 1,234.50 EUR
balance = 1234.5
Interpolation defines __match_args__ as ('value', 'expression', 'conversion', 'format_spec'), so it works with positional class patterns in a match statement (see Pattern matching).
Nested replacement fields in the format spec, like {width} above, are evaluated right away. The Interpolation stores the finished spec '12,.2f', not a nested template.
The real processors below follow the same loop. They only change what happens to part.value.
Safe HTML
The literal text of a t-string was written by the programmer, so it can be trusted. The interpolated values may come from users, so they get escaped with html.escape(). A nested Template was itself written by a programmer, so it's rendered recursively instead of escaped:
from html import escape
from string.templatelib import Template, convert
def html(template: Template) -> str:
if not isinstance(template, Template):
raise TypeError(f"html() expects a t-string, got {type(template).__name__}")
out = []
for part in template:
if isinstance(part, str):
out.append(part) # trusted: written by the programmer
else:
out.append(_html_value(part.value, part.conversion, part.format_spec))
return "".join(out)
def _html_value(value, conversion, format_spec) -> str:
if isinstance(value, Template):
return html(value) # nested t-string: already safe
if isinstance(value, list):
return "".join(_html_value(v, conversion, format_spec) for v in value)
value = convert(value, conversion)
return escape(format(value, format_spec)) # everything else gets escaped
comment = '<script>alert("pwned")</script>'
author = "Bob & Alice"
print(html(t"<p class='comment'>{comment}</p><small>by {author}</small>"))
items = ["<b>milk</b>", "eggs"]
print(html(t"<ul>{[t'<li>{x}</li>' for x in items]}</ul>"))
try:
html(f"<p>{comment}</p>")
except TypeError as e:
print("TypeError:", e)
<p class='comment'><script>alert("pwned")</script></p><small>by Bob & Alice</small>
<ul><li><b>milk</b></li><li>eggs</li></ul>
TypeError: html() expects a t-string, got str
Things to notice:
- The
<li>tags come from a nested t-string, so they stay as markup. The<b>inside the user data is escaped. - The list comprehension inside the braces uses single quotes inside a double-quoted t-string. t-strings follow the same parsing rules as f-strings since Python 3.12, so you could reuse
"there too. - Accidentally writing
finstead oftis caught right away. With an f-string the escaping chance is already gone by the timehtml()is called, because the function only sees the finished string. That's why the check is worth having. A parameter annotated asTemplatealso lets a type checker flag the mistake.
A real HTML library would also handle attribute dicts, Markup-like "already safe" objects and so on, but the core is the loop above.
SQL query parameters
Building SQL with f-strings is the classic injection bug. With a t-string, a processor can replace every interpolation with a ? placeholder and collect the values into a parameter list, which is exactly what sqlite3 and other DB-API drivers want:
import sqlite3
from string.templatelib import Template, Interpolation
def sql(template: Template) -> tuple[str, list]:
query, params = [], []
for part in template:
if isinstance(part, str):
query.append(part)
else:
query.append("?")
params.append(part.value)
return "".join(query), params
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT, age INTEGER)")
for name, age in [("Ada", 36), ("Bob", 41), ("O'Brien", 29)]:
db.execute(*sql(t"INSERT INTO users VALUES ({name}, {age})"))
min_age = 30
query, params = sql(t"SELECT name FROM users WHERE age > {min_age} ORDER BY name")
print(query, params)
print(db.execute(query, params).fetchall())
evil = "x' OR '1'='1"
query, params = sql(t"SELECT name FROM users WHERE name = {evil}")
print(query, params)
print(db.execute(query, params).fetchall())
name = "O'Brien"
print(db.execute(*sql(t"SELECT age FROM users WHERE name = {name}")).fetchone())
SELECT name FROM users WHERE age > ? ORDER BY name [30]
[('Ada',), ('Bob',)]
SELECT name FROM users WHERE name = ? ["x' OR '1'='1"]
[]
(29,)
You write the query with the values in place, which reads like an f-string, and the driver still gets placeholders. The injection attempt is just a strange name that matches no row, and O'Brien needs no quoting.
Composing queries and identifiers
Placeholders only work for values. Table and column names can't be parameters, and you often build a WHERE clause from optional pieces. Both fit naturally: treat a nested Template as a query fragment to merge in, and use a small marker type for identifiers that are validated and inserted as quoted names:
import sqlite3
from string.templatelib import Template
class Ident(str):
"""A table or column name. Validated, then inserted as-is."""
def __new__(cls, name: str):
if not name.isidentifier():
raise ValueError(f"bad identifier: {name!r}")
return super().__new__(cls, name)
def sql(template: Template) -> tuple[str, list]:
query, params = [], []
for part in template:
if isinstance(part, str):
query.append(part)
elif isinstance(part.value, Template): # nested fragment
q, p = sql(part.value)
query.append(q)
params.extend(p)
elif isinstance(part.value, Ident):
query.append(f'"{part.value}"')
else:
query.append("?")
params.append(part.value)
return "".join(query), params
def find(table: str, order_by: str, min_age: int | None = None, city: str | None = None):
conditions = []
if min_age is not None:
conditions.append(t"age >= {min_age}")
if city is not None:
conditions.append(t"city = {city}")
where = t""
for i, cond in enumerate(conditions):
where += (t" WHERE " if i == 0 else t" AND ") + cond
return sql(t"SELECT name FROM {Ident(table)}{where} ORDER BY {Ident(order_by)}")
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE people (name TEXT, age INTEGER, city TEXT)")
db.executemany("INSERT INTO people VALUES (?, ?, ?)",
[("Ada", 36, "London"), ("Bob", 41, "Paris"), ("Cy", 25, "London")])
for args in [{}, {"min_age": 30}, {"min_age": 30, "city": "London"}]:
query, params = find("people", "name", **args)
print(query, params, db.execute(query, params).fetchall())
try:
find("people; DROP TABLE people", "name")
except ValueError as e:
print("ValueError:", e)
SELECT name FROM "people" ORDER BY "name" [] [('Ada',), ('Bob',), ('Cy',)]
SELECT name FROM "people" WHERE age >= ? ORDER BY "name" [30] [('Ada',), ('Bob',)]
SELECT name FROM "people" WHERE age >= ? AND city = ? ORDER BY "name" [30, 'London'] [('Ada',)]
ValueError: bad identifier: 'people; DROP TABLE people'
Templates can be added to each other with + (and +=), which joins their strings and interpolations. The values stay separate from the text the whole time, so the fragments never get a chance to leak user data into the SQL.
Structured log messages
An interpolation knows both its value and the source text of its expression. That's enough to produce a readable message and a dict of fields from the same t-string:
import json
import logging
from string.templatelib import Template, convert
class StructuredMessage:
def __init__(self, template: Template):
self.template = template
def __str__(self) -> str:
text = "".join(
p if isinstance(p, str) else format(convert(p.value, p.conversion), p.format_spec)
for p in self.template
)
fields = {p.expression: p.value for p in self.template.interpolations}
return f"{text} >>> {json.dumps(fields)}"
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger("shop")
user, total, items = "ada", 59.9, 3
log.info(StructuredMessage(t"user {user} paid {total:.2f} for {items} items"))
INFO user ada paid 59.90 for 3 items >>> {"user": "ada", "total": 59.9, "items": 3}
The logging module calls str() on the message object only when the record is actually emitted, so the formatting is skipped for disabled levels. The field values themselves were computed when the t-string was evaluated, though. See Logging for the rest of the logging setup.
Values are evaluated eagerly
A t-string is not a lazy template. Its expressions run immediately, in the scope where the t-string is written, just like in an f-string. Only the formatting is delayed. If you need lazy values, interpolate a callable and let the processor call it:
from string.templatelib import Template
calls = 0
def expensive():
global calls
calls += 1
return "result"
t = t"value: {expensive()}"
print(calls) # already evaluated
print(t.interpolations[0].expression, t.interpolations[0].value)
def render_lazy(template: Template) -> str:
return "".join(
p if isinstance(p, str) else str(p.value() if callable(p.value) else p.value)
for p in template
)
calls = 0
lazy = t"value: {expensive}"
print(calls) # nothing called yet
print(render_lazy(lazy), calls)
lazy2 = t"value: {(lambda: expensive().upper())}"
print(render_lazy(lazy2), calls)
1
expensive() result
0
value: result 1
value: RESULT 2
A lambda has to be wrapped in parentheses inside the braces, because a bare : would start the format spec.
This also means a t-string can't be loaded from a file or a database. It's source code. For templates that come from outside the program, use string.Template or a template engine like Jinja.
Syntax details
Everything you can write in an f-string works in a t-string: conversions, format specs with nested fields, the = debugging specifier, triple quotes and the raw prefix (rt"...", tr"...", in any case combination):
from string.templatelib import Template, Interpolation
x = 7
width = 5
t = t"{x=} {x = :>{width}} {x!s:03}"
print(t.strings)
for i in t.interpolations:
print(i)
path = "C:\\new"
r = rt"\d+ in {path}\n"
print(r.strings)
multi = t"""
SELECT *
FROM {"users"}
"""
print(multi.strings)
built = Template("Hello ", Interpolation("Ada", "name"), "!")
print(built.strings, built.values)
print(Template("a", "b", Interpolation(1, "x"), Interpolation(2, "y")).strings)
combined = t"Hi {x}" + t", width={width}"
print(combined.strings, combined.values)
try:
combined.strings = ()
except AttributeError as e:
print("AttributeError:", e)
('x=', ' x = ', ' ', '')
Interpolation(7, 'x', 'r', '')
Interpolation(7, 'x', None, '>5')
Interpolation(7, 'x', 's', '03')
('\\d+ in ', '\\n')
('\nSELECT *\nFROM ', '\n')
('Hello ', '!') ('Ada',)
('ab', '', '')
('Hi ', ', width=', '') (7, 5)
AttributeError: readonly attribute
Details worth knowing:
{x=}puts the textx=into the literal strings and sets the conversion to'r', unless a format spec is given. That mirrors the f-string rule.Template(...)can be called directly with any mix of strings andInterpolationobjects. Adjacent strings are merged and empty ones are inserted between interpolations, so the "one more string than interpolations" rule always holds.Interpolation(value, expression)defaults to no conversion and an empty format spec.TemplateandInterpolationare immutable.tcan't be combined withf,boru.ft"..."is aSyntaxError: 'f' and 't' prefixes are incompatible.- Implicit concatenation of adjacent literals (
t"a" t"{x}") works as long as all parts are t-strings. Mixingt"..."with a plain or f-string literal is aSyntaxError: cannot mix t-string literals with string or bytes literals.
t-strings, f-strings and string.Template
string.Template is the class from the string module that substitutes $name placeholders at runtime. It's a completely separate thing that happens to share the name:
from string import Template as DollarTemplate
# text that comes from a config file or a translator, not from source code
greeting = DollarTemplate("Hello $name, your order #$order_id has shipped")
print(greeting.substitute(name="Ada", order_id=1017))
print(greeting.get_identifiers())
name, order_id = "Ada", 1017
tmpl = t"Hello {name}, your order #{order_id} has shipped"
print(type(greeting).__module__, type(tmpl).__module__)
Hello Ada, your order #1017 has shipped
['name', 'order_id']
string string.templatelib
Importing it under a different name avoids a clash with string.templatelib.Template in the same file.
| f-string | t-string | string.Template |
|
|---|---|---|---|
| Since | 3.6 | 3.14 | 2.4 |
| Written as | f"{x}" |
t"{x}" |
Template("$x") |
| Result | str |
Template object |
object, .substitute() returns str |
| Template text comes from | source code | source code | anywhere, at runtime |
| Values supplied | evaluated in place | evaluated in place | passed to substitute() later |
| Arbitrary expressions | yes | yes | no, names only |
| Who combines the parts | Python, immediately | your processing function | substitute() |
| Typical use | everyday formatting | escaping, SQL, structured data | user-editable or translated text |
Summary
t"..."(Python 3.14, PEP 750) evaluates like an f-string but returns astring.templatelib.Templateinstead of astr.- A
Templatehasstrings,interpolationsandvalues. Iterating yieldsstrandInterpolationparts in order, without empty strings. - An
Interpolationhasvalue,expression,conversionandformat_spec. Conversions and specs are recorded, not applied. Useconvert()andformat()to apply them. str(template)is just the repr. Templates can't be added tostr, only to other templates.- Write a function that walks the parts to escape HTML, turn values into SQL parameters, or log structured fields. Treat the literal strings as trusted and the values as untrusted.
- Check
isinstance(arg, Template)in such functions so an f-string passed by mistake fails loudly. - Expressions are evaluated immediately. Interpolate callables if you need laziness, and use
string.Templatefor template text that isn't in the source code.