Python 3.14+Strings (str)construct
t-strings
formatting
t'...' looks like an f-string but produces a Template object, not a str: the text parts and interpolated values are kept apart (Python 3.14+).
Syntax
t'текст {выражение}'
T"текст {выражение!r:формат}"
The main trap: a t-string is not a str. It is never equal to a string with the same text (the comparison gives False) and cannot be joined to a str with + (TypeError), and str(tpl) gives the template's repr, not the finished text. Your code builds the string: it iterates over the template, getting text pieces and Interpolation objects, and can, for example, escape values for HTML or SQL. If you just need a string, use an f-string.
Examples
# Python 3.14+
name = 'Bob'
tpl = t'Hi {name}!'
print(type(tpl).__name__) # → Template
print(tpl.strings, tpl.values) # → ('Hi ', '!') ('Bob',)
print(tpl == 'Hi Bob!') # → False
print(str(tpl)[:9]) # → Template( — repr шаблона, а не текст
tpl + '?' # → TypeError
# Python 3.14+
from string.templatelib import Interpolation
name = '<b>'
tpl = t'Hi {name}!'
parts = []
for part in tpl:
if isinstance(part, Interpolation):
part = str(part.value).replace('<', '<').replace('>', '>')
parts.append(part)
print(''.join(parts)) # → Hi <b>!
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy