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.
Python code
9 linesfrom 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
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
- Use template.safe_substitute(name=name) to skip missing placeholders instead of raising an error
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.