String formatting comparison | Pydon't 🐍 | mathspp
PEP 750, which introduces Template Strings (t-strings), has been officially accepted and is set to be included in Python 3.14. This new feature provides a powerful and flexible way to handle string processing, offering developers more control over interpolated values before they are combined into a final string.
t
prefix, similar to f-strings. They evaluate to a new type, Template
, which allows access to both the string and its interpolated values.r
prefix to create raw template strings, preserving escape sequences.While f-strings are popular, they have limitations in scenarios where developers need to transform interpolated values before combining them into a final string. t-strings address these limitations by providing a mechanism to intercept and process interpolated values, enhancing security and flexibility in string processing.
Here’s a simple example of using t-strings for HTML generation with automatic sanitization:
evil = "<script>alert('evil')</script>"
template = t"<p>{evil}</p>"
assert html(template) == "<p><script>alert('evil')</script></p>"
For more detailed examples and use cases, refer to the PEP 750 documentation.
t-strings are a significant addition to Python, offering developers a more robust and flexible way to handle string processing. With their ability to intercept and transform interpolated values, t-strings open up new possibilities for safer and more efficient string manipulation in Python.