Content · Programming · Python

Python string.Template: Simple Text Substitution

Perform readable variable substitution with string.Template.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Perform readable variable substitution with string.Template.

How It Works


string.Template uses $name or ${name} placeholders and substitute(mapping). Missing required variables raise KeyError, while safe_substitute leaves unresolved placeholders unchanged. It does not automatically HTML-escape inserted values.

Step-by-Step Example


from string import Template
message_template = Template('Hello, $person! Your role is ${role}.')
print(message_template.substitute(person='Ava', role='editor'))

Understanding the Example


  • The expression "Template('Hello, $person! Your role is ${role}.')" supplies the value stored as 'message_template'. This value is then used or checked by the later statements.
  • The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.

A successful run of this example prints the following output:

Hello, Ava! Your role is editor.

Where This Fits in a Real Program


Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.

Practice: Try It Yourself


Use $$ to insert a literal dollar sign.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Assuming safe_substitute sanitizes dangerous data or that dollar signs never need escaping.
  • Create a mail greeting template and supply its values from a dictionary.

Key Takeaways


  • Perform readable variable substitution with string.Template.
  • string.Template uses $name or ${name} placeholders and substitute(mapping).
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.