14.8 C
New York
Wednesday, May 14, 2025

How to use template strings in Python 3.14



  • The strings object contains all the static strings in the original template—in this case, the "Hello, " before the variable and the empty string "" after the variable.
  • The interpolations object contains all the interpolations of the different variables in the t-string. Each is a separate Interpolation object with data about its value, the expression used to create it, and other useful details.

If you iterate through the template directly (for item in template:) you would get each element in the template in turn: the string "Hello, ", the Interpolation object shown above, and the string "". This makes it easy to assemble a new string from the elements of a t-string.

Using a template string

Again, the point of a template string isn’t to print it as is, but to pass it to a function that will handle formatting duties. For instance, a simple template string handler to render each variable’s string representation in upper case might look like this:


from string.templatelib import Template, Interpolation
def t_upper(template: Template):
    output = []
    for item in template:
        if isinstance(item, Interpolation):
            output.append(str(item).upper())
        else:
            output.append(item)
    return "".join(output)

If we ran t_upper() on the above template, we would get Hello, DAVIS as the output.

Note that we have an import line in this code:


from string.templatelib import Template, Interpolation

string.templatelib is a new module in the standard library for Python 3.14 that holds the types we need: Template for the type hint to the function, and Interpolation to check the elements we iterate through.

However, we don’t need string.templatelib to make template strings. Those we can construct just by using the t-string syntax anywhere in our code.

A useful template string example

For a better example of how useful and powerful template strings can be, let’s look at a task that would be a good deal more difficult without them.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles