0
0
PythonHow-ToBeginner · 3 min read

How to Use String Template in Python: Simple Guide

In Python, you can use string.Template from the string module to create string templates with placeholders marked by $. You replace placeholders by calling the substitute() method with a dictionary or keyword arguments to fill in values.
📐

Syntax

The string.Template class lets you define a string with placeholders marked by $placeholder. You create a template object and then call substitute() or safe_substitute() to replace placeholders with actual values.

  • Template(template_string): Creates a template object.
  • substitute(mapping_or_kwargs): Replaces placeholders, raises error if missing keys.
  • safe_substitute(mapping_or_kwargs): Replaces placeholders, leaves missing keys unchanged.
python
from string import Template

t = Template('Hello, $name! Welcome to $place.')
result = t.substitute(name='Alice', place='Wonderland')
print(result)
Output
Hello, Alice! Welcome to Wonderland!
💻

Example

This example shows how to create a string template and fill in values using substitute(). It prints a greeting message with the name and place filled in.

python
from string import Template

def greet(name, place):
    template = Template('Hello, $name! Welcome to $place.')
    return template.substitute(name=name, place=place)

print(greet('Bob', 'Python Land'))
Output
Hello, Bob! Welcome to Python Land!
⚠️

Common Pitfalls

One common mistake is forgetting to provide all placeholder values when using substitute(), which causes a KeyError. To avoid this, use safe_substitute() which leaves missing placeholders unchanged instead of raising an error.

Also, placeholders must be valid Python identifiers after the $. Using invalid names or forgetting the $ will not work.

python
from string import Template

t = Template('Hello, $name! Your score is $score.')

# Wrong: missing 'score' key causes KeyError
try:
    print(t.substitute(name='Eve'))
except KeyError as e:
    print(f'Error: missing key {e}')

# Right: safe_substitute leaves $score as is
print(t.safe_substitute(name='Eve'))
Output
Error: missing key 'score' Hello, Eve! Your score is $score.
📊

Quick Reference

FeatureDescriptionExample
Create TemplateMake a template object with placeholdersTemplate('Hi, $name!')
substitute()Replace placeholders, error if missing keyst.substitute(name='Sam')
safe_substitute()Replace placeholders, ignore missing keyst.safe_substitute()
Placeholder formatUse $name or ${name} for placeholders$name or ${name}
Valid namesPlaceholders must be valid Python identifierse.g., $user_name

Key Takeaways

Use string.Template with $ placeholders to create string templates in Python.
Call substitute() with all keys to replace placeholders or safe_substitute() to avoid errors on missing keys.
Placeholders must be valid Python identifiers and start with a $ sign.
Use ${name} syntax if you need to separate placeholder names from surrounding text.
string.Template is useful for simple templating without complex formatting.