Last modified: Sep 03, 2026
Python String Template: A Simple Guide
String formatting is a core skill in Python. You often need to insert values into text. The format() method and f-strings are popular choices. But there is another powerful tool: the Python string template.
This guide explains the Template class. It comes from the string module. It offers a simpler and safer way to build strings. It is perfect for user-generated input. Let's explore how it works.
What is a Python String Template?
A string template uses the Template class. It replaces placeholders with actual values. The placeholders start with a dollar sign ($). You can write $name or ${name} in your text.
This method is different from other formatting styles. It is less verbose. It also avoids complex syntax errors. Beginners find it easier to read and understand.
To use it, you must import the class first. Then, you create a template object. Finally, you call a method to perform the substitution. This process is straightforward and clean.
# Import the Template class
from string import Template
# Create a template string
t = Template('Hello, $name!')
# Substitute the value
result = t.substitute(name='World')
print(result)
Hello, World!
Notice how simple the syntax is. You do not need curly braces or format specifiers. Just use a dollar sign. This makes your code very readable.
Why Use the Template Class?
You might ask, "Why not just use f-strings?" F-strings are fast and powerful. However, the Template class has unique advantages.
The biggest benefit is security. When you accept format strings from users, they could access internal variables. Templates prevent this. They only allow simple substitution. There is no risk of code injection.
Another reason is simplicity. The syntax is minimal. It is also very consistent. If you need to localize your application, templates are excellent. Translators can easily see the placeholders and move them around.
For a deeper look at string basics, you might want to review our guide on What is a Python String? Easy Guide. It helps you build a solid foundation.
Core Methods: substitute and safe_substitute
The Template class provides two main methods. They are substitute() and safe_substitute(). Both replace placeholders, but they handle errors differently.
The substitute() method is strict. If you miss a placeholder, it raises a KeyError. This is useful for debugging. It tells you exactly what is missing.
The safe_substitute() method is more forgiving. If a placeholder is missing, it leaves it as is. It does not raise an error. This is great for optional data or partial templates.
from string import Template
# Using substitute
t = Template('$name likes $food')
try:
result = t.substitute(name='Sam')
except KeyError as e:
print(f"Error with substitute: {e}")
# Using safe_substitute
result_safe = t.safe_substitute(name='Sam')
print(f"Safe result: {result_safe}")
Error with substitute: 'food'
Safe result: Sam likes $food
Notice the difference in the output. The strict method failed. The safe method worked. It simply left the $food placeholder untouched. This flexibility is very handy.
Formatting Rules and Dollar Signs
What if you want to print an actual dollar sign? The Template class has a rule for that. You use two dollar signs ($$) to produce a single dollar sign.
This rule prevents confusion. It tells Python that you do not want a placeholder. It is a literal dollar sign character. This is very important for financial applications or reports.
Here is an example. It shows how to mix placeholders and literal dollar signs. The output will be clear and correct.
from string import Template
# Template with a literal dollar sign
t = Template('Total price is $$${amount}')
result = t.substitute(amount=50)
print(result)
# Another example
t2 = Template('$item costs $${price}')
result2 = t2.substitute(item='Book', price=20)
print(result2)
Total price is $50
Book costs $20
Look at the first example. We used $$ for the literal dollar sign. Then we used ${amount} for the placeholder. The curly braces are optional, but they help separate the placeholder from other text.
Advanced Template Usage
You can customize the Template class. You can change the delimiter if you want. For example, you might prefer using a percent sign (%) instead of a dollar sign. This is possible by overriding the class variable.
This is useful when your text contains many dollar signs. It reduces the chance of accidental substitution. You simply create a subclass and change the delimiter.
from string import Template
# Custom Template class
class MyTemplate(Template):
delimiter = '%'
# Use the custom delimiter
t = MyTemplate('Hello %name, you have %count messages')
result = t.substitute(name='Alice', count=5)
print(result)
Hello Alice, you have 5 messages
This flexibility makes the Template class very powerful. You can adapt it to any situation. You can also change the idpattern to control what characters are allowed in the placeholder names.
Practical Examples and Use Cases
String templates are great for generating configuration files. You can read a template from a file. Then you can fill it with data from a dictionary. This keeps your code clean.
They are also useful for sending emails. You can create a generic email body. Then you can personalize it for each recipient. Let's look at a practical example with a dictionary.
from string import Template
# Data for the template
data = {
'first_name': 'John',
'last_name': 'Doe',
'order_id': '12345'
}
# Template text
email_template = Template("""
Dear $first_name $last_name,
Thank you for your order.
Your order ID is $order_id.
Best regards,
Support Team
""")
# Generate the email
email = email_template.substitute(data)
print(email)
Dear John Doe,
Thank you for your order.
Your order ID is 12345.
Best regards,
Support Team
Notice that we passed the entire dictionary to substitute(). The method matches the keys with the placeholders. This is a very efficient way to manage data. It keeps your code organized and easy to maintain.
If you are working with text manipulation, you might find our guide on Python String Slicing: A Complete Guide useful. It shows you how to extract parts of strings.
Template vs. Other String Methods
You have many tools for string formatting. F-strings are the fastest. The format() method is very powerful. But the Template class is the safest.
F-strings evaluate expressions inside curly braces. This is powerful but can be risky with untrusted input. The format() method can access object attributes. The Template class only does simple mapping.
For most applications, f-strings are the best choice. They are modern and concise. However, when you need to separate the template from the code, templates are superior. This separation is key for internationalization (i18n).
Let's compare them side-by-side for clarity. This will help you decide which one to use.
name = "Alice"
age = 30
# F-string method
f_string = f"{name} is {age} years old."
# format() method
format_string = "{} is {} years old.".format(name, age)
# Template method
from string import Template
t = Template("$name is $age years old.")
template_string = t.substitute(name=name, age=age)
print(f_string)
print(format_string)
print(template_string)
Alice is 30 years old.
Alice is 30 years old.
Alice is 30 years old.
All three produce the same output. The difference is in how they work. F-strings are direct. Templates are indirect. Choose the one that fits your needs best.
Common Pitfalls and How to Avoid Them
One common mistake is forgetting to import the class. You must import Template from the string module. If you forget, you will get a NameError.
Another pitfall is using invalid placeholder names. Placeholder names must follow the rules for Python identifiers. They can contain letters, numbers, and underscores. They cannot start with a number.
Also, remember that $ is special. If you need a literal dollar sign, you must use $$. Forgetting this will cause a ValueError if the text after the dollar sign is not a valid placeholder.
from string import Template
# This will raise an error
try:
t = Template('Price is $5')
result = t.substitute()
print(result)
except ValueError as e:
print(f"ValueError: {e}")
# Correct way
t2 = Template('Price is $$5')
result2 = t2.substitute()
print(result2)
ValueError: Invalid placeholder in string: line 1, col 11
Price is $5
Always be careful with your syntax. It is better to use $$ for currency. Or, you can use ${'5'} but that is not a placeholder. Just use $$.
Performance Considerations
Is the Template class slow? Yes, it is generally slower than f-strings. For simple operations, this difference is negligible. However, in a tight loop with thousands of iterations, you might notice it.
If performance is your top priority, stick with f-strings. They are optimized for speed. Use templates when you need the safety and flexibility they offer. Do not sacrifice security for a few milliseconds.
For most real-world applications, the speed difference is not a problem. The clarity and safety you gain are worth more. Always profile your code to see if it is actually a bottleneck.
If you are working with large strings, you might be interested in memory usage. Check out our article on Python String Size: Measure Memory & Length for more details.
Conclusion
The Python string template is a valuable tool. It provides a simple and secure way to format strings. The Template class uses dollar signs for placeholders. It is perfect for user input and internationalization.
We covered the substitute() and safe_substitute() methods. We also learned how to handle dollar signs. We saw how to customize the delimiter for special cases. This knowledge will help you write safer and cleaner code.
While f-strings are great for quick tasks, templates excel in specific scenarios. They keep your code secure and your templates portable. Try using them in your next project. You will appreciate their simplicity and robustness.