Skip to content
Python Basics: Filling Text with string.Template

Python Basics: Filling Text with string.Template

October 12, 2026

For a short message with a few named fields, string.Template provides simple dollar-sign placeholders. Keep the wording in a template and supply the values separately.

Use Python 3.12 or newer on Linux. Each example runs independently with the standard library and only prints sample data.

Fill named placeholders

Save as demo_string_template_1.py:

from string import Template

message_template = Template("Hello, $name. You have $count updates.")
message_values = {"name": "Mina", "count": 3}
print(message_template.substitute(message_values))

Run it:

python3 demo_string_template_1.py

Output:

Hello, Mina. You have 3 updates.

substitute() returns a new string using dictionary keys as placeholder names. You can also pass values as keyword arguments. Missing keys raise KeyError, making incomplete data visible.

Separate names and escape dollar signs

Save as demo_string_template_2.py:

from string import Template

filename_template = Template("${stem}_report.txt")
price_template = Template("Price: $$$amount")
print(filename_template.substitute(stem="weekly"))
print(price_template.substitute(amount="12.50"))

Run it:

python3 demo_string_template_2.py

Output:

weekly_report.txt
Price: $12.50

Braces mark the end of a placeholder when more identifier characters follow it. Without braces, $stem_report would be a single name. $$ produces a literal dollar sign; the remaining $amount supplies the value. Prepare formatted numbers before substitution.

Check a template and preview missing values

Save as demo_string_template_3.py:

from string import Template

status_template = Template("$task: $status")
print(status_template.is_valid())
print(status_template.get_identifiers())
print(status_template.safe_substitute(task="Backup"))
try:
    status_template.substitute(task="Backup")
except KeyError as error:
    print("Missing:", error.args[0])

Run it:

python3 demo_string_template_3.py

Output:

True
['task', 'status']
Backup: $status
Missing: status

is_valid() checks placeholder syntax, not whether values are available. get_identifiers() lists the valid names in first-appearance order. Both methods are available in Python 3.11 and newer.

safe_substitute() leaves missing placeholders in the result and can silently preserve malformed syntax. Use it for an intentional partial preview; prefer substitute() when every field must be filled.

Template substitution does not escape HTML or sanitize values for commands or queries. Handle escaping or parameterization for the destination separately; the word “safe” does not provide that protection.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on