Header add

In this article we will learn about template strings, or t-strings, which arrived in Python 3.14. If you have used f-strings, the syntax will look very familiar. The behaviour is different though, and that difference is the whole point of the feature.

I will keep it practical. We will check the Python version, write our first t-string, look inside the object it creates, and then write three small functions that process it: a plain renderer, an HTML-safe renderer and a parameterized SQL builder. At the end I have listed the mistakes I made the first time I tried them.

Python 3.14 template strings (t-strings) cover banner with a code window showing a t-string

What is a t-string?

A t-string is written exactly like an f-string, only with a t prefix instead of f. The big change is what you get back.

An f-string is evaluated straight away and gives you a finished str. A t-string gives you a Template object from the new string.templatelib module. The static text and the values stay separate, so your code can inspect them and decide how to join them.

Why does that matter? With an f-string, user input is glued into the text before you get a chance to check it. With a t-string, you get the pieces first. You can escape values for HTML, turn them into SQL parameters, or log them as structured data.

Python t-strings vs f-strings flow: an f-string returns a str, a t-string returns a Template processed by your function
Featuref-stringt-string
Prefixf"..."t"..."
Available fromPython 3.6Python 3.14
Result typestrstring.templatelib.Template
Conversions like !r and specs like :.2fApplied automaticallyStored; your code decides
Can be combined with rYes (rf, fr)Yes (rt, tr)

Step 1: Check your Python version

T-strings need Python 3.14 or later. On older versions t"..." is simply a syntax error. Open a terminal and run:

python --version

On Windows you can also use the launcher with py --version. If you see 3.13 or lower, install 3.14 from python.org before you continue.

Step 2: Write your first t-string

Create a file called demo.py and add this code:

from string.templatelib import Template, Interpolation

name = "Jayant"
city = "Bhubaneswar"
greeting = t"Hello {name}, welcome from {city}!"

print(type(greeting))
print(greeting.strings)
print(greeting.values)
print(greeting.interpolations[0].expression)

Run it with python demo.py and you get:

<class 'string.templatelib.Template'>
('Hello ', ', welcome from ', '!')
('Jayant', 'Bhubaneswar')
name

So the template keeps three things for us:

  1. strings is a tuple of the static text parts. It always has one more item than there are interpolations.
  2. interpolations is a tuple of Interpolation objects, one for each {...} in the string.
  3. values is a shortcut that gives just the evaluated values.

Each Interpolation has four attributes: value (the evaluated result), expression (the source text inside the braces, here 'name'), conversion ('r', 's', 'a' or None) and format_spec (for example '.2f').

Anatomy of a Python t-string Template object showing strings, interpolations and values

You can also loop over a template. Iteration gives you the text parts and the Interpolation objects in order, and it skips any empty strings:

for part in greeting:
    print(repr(part))
'Hello '
Interpolation('Jayant', 'name', None, '')
', welcome from '
Interpolation('Bhubaneswar', 'city', None, '')
'!'

Step 3: Write a simple render function

A template does not turn itself into a string. That job belongs to a function you write. Here is one that behaves like an f-string. It uses the convert() helper from the same module to apply !r, !s or !a, and the built-in format() for the format spec.

from string.templatelib import Template, convert

def render(template: Template) -> str:
    parts = []
    for item in template:
        if isinstance(item, str):
            parts.append(item)
        else:
            value = convert(item.value, item.conversion)
            parts.append(format(value, item.format_spec))
    return "".join(parts)

name = "Jayant"
price = 1499.5
print(render(t"Total for {name!r}: {price:,.2f}"))

Output:

Total for 'Jayant': 1,499.50

That is the same text you would get from the f-string version. Not very exciting yet, but now we control every value before it lands in the result.

Step 4: Escape values for HTML

Say you are building a small HTML snippet from a user comment. With an f-string, a comment containing a <script> tag goes straight into your page. With a t-string we can escape only the dynamic parts and leave our own markup alone:

import html
from string.templatelib import Template

def safe_html(template: Template) -> str:
    parts = []
    for item in template:
        if isinstance(item, str):
            parts.append(item)
        else:
            parts.append(html.escape(str(item.value)))
    return "".join(parts)

comment = "<script>alert('hi')</script>"
print(safe_html(t"<p>{comment}</p>"))

Output:

<p>&lt;script&gt;alert(&#x27;hi&#x27;)&lt;/script&gt;</p>

The <p> tags we wrote stay as they are. Only the user's text is escaped.

Step 5: Build a parameterized SQL query

This is the example that made t-strings click for me, because as a .NET developer I have always been told to use SqlParameter instead of string concatenation. The same idea works here. Each interpolation becomes a ? placeholder and its value goes into a separate list:

from string.templatelib import Template

def to_sql(template: Template) -> tuple[str, list]:
    sql_parts = []
    params = []
    for item in template:
        if isinstance(item, str):
            sql_parts.append(item)
        else:
            sql_parts.append("?")
            params.append(item.value)
    return "".join(sql_parts), params

user_input = "Ravi'; DROP TABLE Users; --"
query, params = to_sql(t"SELECT * FROM Users WHERE Name = {user_input}")
print(query)
print(params)

Output:

SELECT * FROM Users WHERE Name = ?
["Ravi'; DROP TABLE Users; --"]

You can pass query and params straight to cursor.execute(query, params) in the built-in sqlite3 module, which uses ? placeholders. The database treats the input as a plain value, so the injection attempt does nothing. Other drivers may use a different placeholder style, so check yours before you copy this. Treat this as a teaching example, not a full query builder.

Python t-strings for safe SQL: f-string query text compared with a t-string turned into a parameterized query

Common mistakes with t-strings

These are the three that caught me out:

  1. Printing a template expecting text. Template has no special __str__, so print(greeting) shows the repr, something like Template(strings=(...), interpolations=(...)). Pass it through your render function first.
  2. Adding a plain string to a template. greeting + " Have a nice day." raises TypeError: can only concatenate string.templatelib.Template (not "str") to string.templatelib.Template. Wrap the text instead: greeting + Template(" Have a nice day.").
  3. Combining f and t. A prefix like tf"..." is a SyntaxError ("'f' and 't' prefixes are incompatible"). Pick one. The raw forms rt and tr are fine.

Also remember that a t-string does not apply !r or :.2f for you. Those are stored on the Interpolation, and your function decides whether to use them, as we did with convert() and format() in Step 3.

Conclusion

In this article we learned what Python 3.14 template strings are and how they differ from f-strings. A t-string gives you a Template with the static text and the values kept apart. That small change lets you write your own processing: an f-string style renderer, an HTML-safe renderer and a parameterized SQL builder, all in a few lines. I expect libraries for HTML, SQL and logging to start accepting templates directly, so it is worth getting comfortable with them now.

If you are on Python 3.14, try the examples above and tell me in the comments how you plan to use t-strings in your own projects. If you get stuck on any step, leave a comment and I will help.

Note: The images in this post are illustrations to explain each step.

Post a Comment

Previous Post Next Post