Python string templates
Fill $placeholders in text you did not write, and know where the approach runs out.
A Python string template is a piece of text with $name placeholders that you fill in later. The class is string.Template, it lives in the standard library, and it is the simplest of Python's three ways to put values into a string.
The short answer
from string import Template
greeting = Template("Hello, $name. Your order ships on $day.")
print(greeting.substitute(name="Ada", day="Friday"))
substitute takes keyword arguments, a dictionary, or both. The template is not changed, so you can build it once and fill it as many times as you like.
$name, ${name} and $$
There are three pieces of syntax and no more:
$nameis a placeholder. The name follows the rules for a Python identifier.${name}is the same placeholder with braces, for when it is followed directly by letters or digits.$$is a literal dollar sign.
bill = Template("$who owes ${amount}USD, plus a $$5 fee.")
print(bill.substitute(who="Ada", amount=20))
# Ada owes 20USD, plus a $5 fee.
Without the braces, Python would look for a value called amountUSD. And a dollar sign that is not followed by a valid name is an error in substitute:
try:
Template("Cost: $5").substitute()
except ValueError as e:
print(e) # Invalid placeholder in string: line 1, col 7
substitute or safe_substitute?
substitute is strict. If a placeholder has no value, it raises a KeyError naming the one that is missing:
try:
bill.substitute(who="Ada")
except KeyError as e:
print(f"missing: {e}") # missing: 'amount'
safe_substitute never raises. It fills in what it can and leaves the rest exactly as written:
print(bill.safe_substitute(who="Ada"))
# Ada owes ${amount}USD, plus a $5 fee.
Use substitute by default. An error in testing is better than a customer email that reads "Hello, $name". safe_substitute earns its place when you fill a template in two passes, or when the text may contain stray dollar signs you cannot control.
To see what a template expects before filling it, ask:
print(bill.get_identifiers()) # ['who', 'amount']
That method arrived in Python 3.11.
Why it exists alongside f-strings and str.format
An f-string is evaluated the moment Python reaches it, in your source code. It cannot be loaded from a file or typed in by a user. str.format can, but it is too powerful to hand to strangers, because a format string can reach into the objects you pass it:
class Account:
def __init__(self):
self.owner = "Ada"
self.api_key = "hunter2"
account = Account()
print("Hi {a.owner}, {a.api_key}".format(a=account))
# Hi Ada, hunter2
If a customer writes that template, they have just read a field you never meant to expose. string.Template cannot do this. A placeholder is a name and nothing else: no attribute access, no indexing, no format specs.
print(Template("Hi $a.api_key").safe_substitute(a="Ada"))
# Hi Ada.api_key
So the rule of thumb is: f-strings for text written in your own code, string.Template for text that comes from a config file, a database, a translator or a user.
Filling a Python HTML template
A template can hold HTML as easily as plain text. Given a file card.html:
<article class="card">
<h2>$title</h2>
<p>$summary</p>
<a href="$url">Read more</a>
</article>
read it, wrap it, and substitute:
import html
from pathlib import Path
card = Template(Path("card.html").read_text(encoding="utf-8"))
print(card.substitute(
title=html.escape("Tea & cake"),
summary=html.escape("Why <b> tags are not for emphasis"),
url="/posts/tea",
))
which prints:
<article class="card">
<h2>Tea & cake</h2>
<p>Why <b> tags are not for emphasis</p>
<a href="/posts/tea">Read more</a>
</article>
This works well for a fixed layout with a few slots. It has two limits, and you reach them quickly:
- No escaping.
Templateknows nothing about HTML. Leave outhtml.escapeon one value and a stray<breaks the page, or a<script>in user input runs. - No loops or conditions. A list of cards means filling the template once per item in Python and joining the results. An optional section means building that fragment separately and passing it in as a value.
row = Template("<li>$name</li>")
drinks = ["Tea & cake", "Coffee"]
print("".join(row.substitute(name=html.escape(d)) for d in drinks))
# <li>Tea & cake</li><li>Coffee</li>
After a few of those, the logic lives in Python and the markup is scattered across small template strings.
When the template needs logic: Nitro UI
If you are already writing the loops in Python, you can write the HTML there too. Nitro UI (pip install nitro-ui) builds elements as objects and escapes text for you:
from nitro_ui import ListItem, UnorderedList
menu = UnorderedList(*[ListItem(d) for d in drinks])
print(menu.render())
# <ul><li>Tea & cake</li><li>Coffee</li></ul>
A condition is an ordinary if, a repeated block is a function, and there is no escaping to remember. What you give up is the thing string.Template is best at: a template that a non-programmer can edit, or that is safe to accept from a user. Keep string.Template for those, and for plain text such as emails and config files. The other options are compared in generate HTML with Python.
Common questions
Can I change the $ delimiter? Yes. Subclass Template and set delimiter = "%" or whatever you need. It helps when the text is full of real dollar signs, such as shell scripts or price lists.
Is string.Template slower than an f-string? Yes, by a wide margin, since it runs a regular expression on every call. It rarely matters outside a tight loop.
Can a placeholder format a number, like {price:.2f}? No. Format the value before you pass it in: substitute(price=f"{price:.2f}").
Is it the same as the template strings added in Python 3.14? No. Those are t-strings, written t"..." in source code like f-strings. string.Template is the older class for text loaded at run time.
This page uses Nitro UI.
Create HTML with Python classes instead of strings. Type-safe, autocomplete-friendly, zero dependencies.
$ pip install nitro-ui