Process Data with Template Strings in Python 3.14

Process Data with Template Strings in Python 3.14

Working with dynamic strings is a common task in Python, especially when handling user input, generating markup, or building domain-specific text formats. Developers typically relied on f-strings or external templating engines, which immediately produce a final string and leave little room for inspection or transformation.

Since Python 3.14, we can use template strings (t-strings) that allow us to work with string content before it is fully rendered. By using the new t prefix, we can access both the static text and the interpolated values separately, enabling safer and more flexible string processing directly in the standard library.

At first glance, template strings look similar to f-strings, but instead of returning a plain str, they produce a Template object. This object can be iterated over to examine its individual parts.

Here's a minimal example that sanitizes user input by escaping HTML-sensitive characters using template string:

from string.templatelib import Interpolation

def escape_html(template):
    parts = []
    for part in template:
        if isinstance(part, Interpolation):
            parts.append(str(part.value).replace('<', '&lt;').replace('>', '&gt;'))
        else:
            parts.append(part)

    return ''.join(parts)

user_input = '<b>John</b>'
output = escape_html(t'Hello, {user_input}')
print(output) # Hello, &lt;b&gt;John&lt;/b&gt;

Instead of blindly embedding user_input into the string, the template exposes it as a distinct interpolation object. This makes it easy to transform or validate the value before combining it with the surrounding text.

Unlike f-strings, which immediately evaluate to a final result, template strings preserve structure. Each literal segment and each interpolation is kept separate until we decide how to handle it. This design opens the door to a wide range of use cases:

  • Escaping or validating user input.
  • Generating safe HTML, SQL, or shell commands.
  • Custom logging and formatting pipelines.
  • Lightweight domain-specific languages (DSLs).

Template strings also scale well for more complex or repetitive processing. Because we can iterate over their components, we can apply consistent rules across many interpolations without parsing or re-tokenizing raw strings.

Leave a Comment

Cancel reply

Your email address will not be published.