Python 3.14 is introducing template strings, so-called t-strings. Can someone explain how these differ from f-strings? What new problems are t-strings helping developers solve?
The new t-strings ease the creation of strings meant to represent other languages, embedded in a Python program, while preserving information about the variables and expressions interpolated so that specialized glue/connection code to that other language can do things like syntax checking, character escaping, security auditing, and in general adding specific punctuation to those interpolated values. The full proposal is in PEP 750.
The important thing to have in mind is that a t-string by itself adds no value. Just when combined with a call to a consumer of that string, which might be a SQL connector, an HTML renderer, or even a regular expression template, the extra information - when compared with an f-string - present in the t-string will add value.
In other words, while an f-string is immediately rendered into an immutable, plain str
instance when found, a t-string is converted into a Template object which preserves information about the individual interpolated values (and if needed, their original expressions). This template instance is then passed to a call which will act on the string, special casing these values. For example, a t-string aware SQL connector can automatically escape in a safe way all interpolated values, mitigating any possible SQL injection vulnerability.
For a simple usage example not in the docs, here is a simple interactive mode snippet which will wrap the templated values in a CSI ANSI code sequence to change the terminal color. I set up constant values with the color codes I am using for the example:
In [26]: from string import templatelib
In [27]: red = 31; reset=0; green = 32
In [28]: a = t"The next {red}text{reset} should be {green}in another color{reset}"
In [29]: for part in a:
...: if isinstance(part, templatelib.Interpolation):
...: part = f"\x1b[{part.value}m"
...: print(part, end="")
...:
This prints some text colored according to the example in a functional terminal (not windows CMD).
Still in this summary, it is worth noting that t-strings, like f-strings are eagerly evaluated. This means the values for the variables in the interpolated expressions are used as they are when the line of code where the t-string is expressed is executed: even if the variable changes later on, the orignal value is saved in the template object. The converse behavior, having the values dynamically change with the values assigned to the variables in the expressions was reasoned out in the discussions leading to the feature. (check the rejected ideas session in PEP 750)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With