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.

Answer from bwk on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί template-class-in-python
String Template Class in Python - GeeksforGeeks
July 23, 2025 - String Template class from Python’s string module provides a simple, $-based way to perform string substitutions. It’s ideal for user-facing text, email templates and config files.
Discussions

python - advanced string formatting vs template strings - Stack Overflow
This is old but it is worth mentioning that one great advantage of using Template Strings is that it is safe when you are accepting the template from un-trusted source. This can be from a configuration file for instance. ... CONFIG = {"SECRET_KEY": "super secret key"} class Event: def ... More on stackoverflow.com
🌐 stackoverflow.com
Template strings in Python 3.14: an useful new feature or just an extra syntax?
This seems useful to formalize what templating systems already do. More on reddit.com
🌐 r/Python
98
167
May 1, 2025
stringtemplate - Example of subclassing string.Template in Python? - Stack Overflow
Advanced usage: you can derive subclasses of Template to customize the placeholder syntax, delimiter character, or the entire regular expression used to parse template strings. To do this, you can override these class attributes: More on stackoverflow.com
🌐 stackoverflow.com
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
🌐 r/Python
29
78
December 17, 2017
🌐
Tutorialspoint
tutorialspoint.com β€Ί python β€Ί using_string_template_class.htm
Python - String Template Class
from string import Template student = {'name':'Rajesh', 'age':23} temp_str = "My name is $name and I am $age years old" tempobj = Template(temp_str) ret = tempobj.substitute(**student) print (ret)
🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί string.templatelib.html
string.templatelib β€” Support for template string literals
The most common way to create a Template instance is to use the template string literal syntax. This syntax is identical to that of f-strings, except that it uses a t prefix in place of an f: >>> cheese = 'Red Leicester' >>> template = t"We're fresh out of {cheese}, sir." >>> type(template) <class 'string.templatelib.Template'>
Top answer
1 of 6
41

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.

2 of 6
29

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. the s in %(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. %s or %(name)s This 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.

🌐
Stack Abuse
stackabuse.com β€Ί formatting-strings-with-the-python-template-class
Formatting Strings with the Python Template Class
September 19, 2021 - The Python Template class is intended to be used for string substitution or string interpolation. The class works using regular expressions and allows for deep customization
🌐
AskPython
askpython.com β€Ί home β€Ί python template strings
Python Template Strings - AskPython
August 6, 2022 - Python's Template String Class provides a way for simple string substitution, wherein the template fields are substituted with suitable replacement strings
Find elsewhere
🌐
Python
peps.python.org β€Ί pep-0750
PEP 750 – Template Strings - Python Enhancement Proposals
July 8, 2024 - Template strings evaluate to an instance of a new immutable type, string.templatelib.Template: class Template: strings: tuple[str, ...] """ A non-empty tuple of the string parts of the template, with N+1 items, where N is the number of interpolations in the template.
🌐
Educative
educative.io β€Ί answers β€Ί string-templates-in-python
String templates in Python
String templates in Python simplify generating dynamic outputs while separating program logic from output formats. Using the string.Template class with methods like substitute() and safe_substitute(), developers can create customizable web pages, ...
🌐
Real Python
realpython.com β€Ί python-t-strings
Python 3.14: Template Strings (T-Strings) – Real Python
May 30, 2025 - Instead of directly evaluating the literal to a string, Python evaluates t-string literals to an instance of Template. This class gives you direct access to the string and its input values before they get combined to create the final string.
🌐
Reddit
reddit.com β€Ί r/python β€Ί template strings in python 3.14: an useful new feature or just an extra syntax?
r/Python on Reddit: Template strings in Python 3.14: an useful new feature or just an extra syntax?
May 1, 2025 -

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?

🌐
Compile N Run
compilenrun.com β€Ί python tutorial β€Ί python strings β€Ί python string templates
Python String Templates | Compile N Run
You can create your own template class with different delimiters: from string import Template # Create a custom template class class CustomTemplate(Template): # Change the delimiter from $ to % delimiter = '%' # Use the custom template ...
🌐
Runebook.dev
runebook.dev β€Ί en β€Ί docs β€Ί python β€Ί library β€Ί string β€Ί string.Template
Python's string.Template Explained: Issues, Fixes, and Alternatives (f-strings vs. Templates)
The string. Template class, found in Python's standard string module, provides a very basic templating mechanism. Its main purpose is to offer safer string substitution compared to other methods like f-strings or
🌐
TutorialsPoint
tutorialspoint.com β€Ί string-template-class-in-python
String Template Class in Python?
July 30, 2019 - from string import Template student = {'name':'Rajesh', 'age':23} temp_str = "My name is $name and I am $age years old" tempobj = Template(temp_str) ret = tempobj.substitute(**student) print (ret)
🌐
ThoughtCo
thoughtco.com β€Ί pythons-string-templates-2813675
The Power of Python's String Templates
December 31, 2018 - Aside from the string constants and the deprecated string functions, which moved to string methods, Python's string module also includes string templates. The template itself is a class that receives a string as its argument. The object instantiated ...
🌐
CodeRivers
coderivers.org β€Ί blog β€Ί python-string-templates
Python String Templates: A Comprehensive Guide - CodeRivers
February 22, 2026 - Python's string.Template class provides a simple way to substitute values into strings. A string template is a string that contains placeholders. These placeholders are marked with a specific delimiter (by default, $).
🌐
Towards Data Science
towardsdatascience.com β€Ί home β€Ί latest β€Ί python template string formatting method
Python Template String Formatting Method | Towards Data Science
January 21, 2025 - It uses Template class from string module. It has a syntax somewhat similar to .format() when done with keywords, but instead of curly braces to define the placeholder, it utilises a dollar sign ($).
Top answer
1 of 1
37

From python docs:

Advanced usage: you can derive subclasses of Template to customize the placeholder syntax, delimiter character, or the entire regular expression used to parse template strings. To do this, you can override these class attributes:

  • delimiter – This is the literal string describing a placeholder introducing delimiter. The default value $. Note that this should not be a regular expression, as the implementation will call re.escape() on this string as needed.

  • idpattern – This is the regular expression describing the pattern for non-braced placeholders (the braces will be added automatically as appropriate). The default value is the regular expression [_a-z][_a-z0-9]*.

Example:

from string import Template

class MyTemplate(Template):
    delimiter = '#'
    idpattern = r'[a-z][_a-z0-9]*'

>>> s = MyTemplate('#who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes $what'

In python 3:

New in version 3.2.

Alternatively, you can provide the entire regular expression pattern by overriding the class attribute pattern. If you do this, the value must be a regular expression object with four named capturing groups. The capturing groups correspond to the rules given above, along with the invalid placeholder rule:

  • escaped – This group matches the escape sequence, e.g. $$, in the default pattern.
  • named – This group matches the unbraced placeholder name; it should not include the delimiter in capturing group.
  • braced – This group matches the brace enclosed placeholder name; it should not include either the delimiter or braces in the capturing group.
  • invalid – This group matches any other delimiter pattern (usually a single delimiter), and it should appear last in the regular expression.

Example:

from string import Template
import re

class TemplateClone(Template):
    delimiter = '$'
    pattern = r'''
    \$(?:
      (?P<escaped>\$) |   # Escape sequence of two delimiters
      (?P<named>[_a-z][_a-z0-9]*)      |   # delimiter and a Python identifier
      {(?P<braced>[_a-z][_a-z0-9]*)}   |   # delimiter and a braced identifier
      (?P<invalid>)              # Other ill-formed delimiter exprs
    )
    '''

class TemplateAlternative(Template):
    delimiter = '[-'
    pattern = r'''
    \[-(?:
       (?P<escaped>-) |            # Expression [-- will become [-
       (?P<named>[^\[\]\n-]+)-\] | # -, [, ], and \n can't be used in names
       \b\B(?P<braced>) |          # Braced names disabled
       (?P<invalid>)               #
    )
    '''

>>> t = TemplateClone("$hi sir")
>>> t.substitute({"hi": "hello"})
'hello sir'

>>> ta = TemplateAlternative("[-hi-] sir")
>>> ta.substitute({"hi": "have a nice day"})
'have a nice day sir'
>>> ta = TemplateAlternative("[--[-hi-]-]")
>>> ta.substitute({"hi": "have a nice day"})
'[-have a nice day-]'

Apparently it is also possible to just omit any of the regex groups escaped, named, braced or invalid to disable it.

🌐
Python
peps.python.org β€Ί pep-0501
PEP 501 – General purpose template literal strings | peps.python.org
August 8, 2015 - However, rather than being rendered directly into a formatted string, these components are instead organised into instances of new types with the following behaviour: class TemplateLiteralText(str): # This is a renamed and extended version of the DecodedConcrete type in PEP 750 # Real type would be implemented in C, this is an API compatible Python equivalent _raw: str def __new__(cls, raw: str): decoded = raw.encode("utf-8").decode("unicode-escape") if decoded == raw: decoded = raw text = super().__new__(cls, decoded) text._raw = raw return text @staticmethod def merge(text_segments:Sequence[
🌐
Python
docs.python.org β€Ί 2.4 β€Ί lib β€Ί node109.html
4.1.2 Template strings
December 15, 2019 - The string module provides a Template class that implements these rules.