How to Use Template Strings for Substitution in Python

This code shows how to use Python's Template class for safe string substitution, replacing placeholders like $name with actual values.

Easy Python 3.9+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

9 lines
Python 3.9+
from string import Template

def format_user_message(name, role, company):
    template = Template("Hello $name! We are glad to have you as our $role at $company.")
    return template.substitute(name=name, role=role, company=company)

if __name__ == "__main__":
    result = format_user_message("Alice", "Python Developer", "TechCorp")
    print(result)

Output

stdout
Hello Alice! We are glad to have you as our Python Developer at TechCorp.

How it works

The Template class from the string module provides a simple way to do string substitution with $-based placeholders. Unlike f-strings or .format(), Template.substitute() treats the template as data, not code, making it safer when template strings come from untrusted sources. The substitute() method replaces all placeholders in one call; if a placeholder is missing or unknown, it raises an error. This makes it ideal for user-facing templates where you want to avoid accidental format-string injection.

Common mistakes

  • Using $name without braces when followed by letters or digits, causing incorrect matches
  • Forgetting that missing keys cause KeyError with substitute() — use safe_substitute() to leave unknowns untouched
  • Confusing Template with f-strings; Template does not evaluate expressions, only substitutes values

Variations

  1. Use template.safe_substitute(name=name) to skip missing placeholders instead of raising an error
  2. Build templates from files or configuration using Template(open('message.txt').read())

Real-world use cases

  • Generating personalized email or notification messages from user data in a web application.
  • Creating SQL queries or CLI command strings with dynamic values while keeping the template readable and safe.
  • Building report templates that get filled with values from a database for automated document generation.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.