One key advantage of string templates is that you can substitute only some of the placeholders using the safe_substitute method. Normal format strings will raise an error if a placeholder is not passed a value. For example:
"Hello, {first} {last}".format(first='Joe')
raises:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'last'
But:
from string import Template
Template("Hello, $first $last").safe_substitute(first='Joe')
Produces:
'Hello, Joe $last'
Note that the returned value is a string, not a Template; if you want to substitute the $last you'll need to create a new Template object from that string.
python - advanced string formatting vs template strings - Stack Overflow
Template strings in Python 3.14: an useful new feature or just an extra syntax?
stringtemplate - Example of subclassing string.Template in Python? - Stack Overflow
how to do multi-line f string without the indentation mess
Why not split the f string?
from uuid import uuid4
a = (
f"""{uuid4()}\n"""
f"""and another line {uuid4()}""")
print(a) More on reddit.com Videos
One key advantage of string templates is that you can substitute only some of the placeholders using the safe_substitute method. Normal format strings will raise an error if a placeholder is not passed a value. For example:
"Hello, {first} {last}".format(first='Joe')
raises:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'last'
But:
from string import Template
Template("Hello, $first $last").safe_substitute(first='Joe')
Produces:
'Hello, Joe $last'
Note that the returned value is a string, not a Template; if you want to substitute the $last you'll need to create a new Template object from that string.
Templates are meant to be simpler than the the usual string formatting, at the cost of expressiveness. The rationale of PEP 292 compares templates to Python's %-style string formatting:
Python currently supports a string substitution syntax based on C's
printf()'%' formatting character. While quite rich, %-formatting codes are also error prone, even for experienced Python programmers. A common mistake is to leave off the trailing format character, e.g. thesin%(name)s.In addition, the rules for what can follow a % sign are fairly complex, while the usual application rarely needs such complexity. Most scripts need to do some string interpolation, but most of those use simple "stringification" formats, i.e.
%sor%(name)sThis form should be made simpler and less error prone.
While the new .format() improved the situation, it's still true that the format string syntax is rather complex, so the rationale still has its points.
Python foundation just accepted PEP 750 for template strings, or called t-strings. It will come with Python 3.14.
There are already so many methods for string formatting in Python, why another one??
Here is an article to dicsuss its usefulness and motivation. What's your view?