Skip to main content

Python String Templates

When working with strings in Python, you often need to insert values into them dynamically. While f-strings and the format() method are popular options, Python also provides another powerful approach: String Templates. This feature offers a simpler and safer alternative for string formatting, especially useful in certain scenarios.

Introduction to String Templates

String Templates were introduced in Python 2.4 as part of PEP 292 and are available through the string module. They provide a way to substitute variables into strings using placeholders.

The main advantages of String Templates include:

  • Simple syntax with $name placeholders
  • Less prone to security issues compared to other formatting methods
  • User-friendly error messages
  • Ideal for user-supplied formatting strings

Let's dive in to understand how they work and when to use them!

Basic Usage of String Templates

Importing the Template Class

First, you need to import the Template class from the string module:

python
from string import Template

Creating and Using a Template

To create a template, define a string with placeholders prefixed by a dollar sign ($):

python
# Creating a template
greeting_template = Template("Hello, $name! Welcome to $place.")

# Using the template with substitute() method
result = greeting_template.substitute(name="Alice", place="Wonderland")
print(result)

Output:

Hello, Alice! Welcome to Wonderland.

Placeholder Syntax

String Templates support two main ways to define placeholders:

  1. Simple placeholder: $name
  2. Bracketed placeholder: ${name} (useful when the placeholder is immediately followed by other text)
python
# Using bracketed placeholders
template = Template("${noun}${suffix} is better than $noun.")
result = template.substitute(noun="code", suffix="r")
print(result)

Output:

coder is better than code.

Template Methods

The Template class provides two main methods for substituting values:

The substitute() Method

This method replaces all placeholders with corresponding values:

python
template = Template("$name is $age years old.")
try:
# All placeholders must be provided
result = template.substitute(name="Bob")
print(result)
except KeyError as e:
print(f"Error: Missing placeholder {e}")

Output:

Error: Missing placeholder 'age'

The safe_substitute() Method

This method is more forgiving—it leaves unmatched placeholders unchanged:

python
template = Template("$name is $age years old.")
# Missing placeholders remain as is
result = template.safe_substitute(name="Bob")
print(result)

Output:

Bob is $age years old.

Use Cases for String Templates

1. User-Supplied Format Strings

String Templates are safer when dealing with format strings that come from users:

python
# User input could be malicious with f-strings or format()
user_template = "$name's score is $score"
template = Template(user_template)
result = template.substitute(name="Charlie", score=85)
print(result)

Output:

Charlie's score is 85

2. Email Templates

They're perfect for creating email templates:

python
email_template = Template("""
Subject: $subject

Dear $recipient,

Thank you for your $action. We will process your request within $timeframe.

Best regards,
$sender
""")

email = email_template.substitute(
subject="Order Confirmation",
recipient="Mr. Smith",
action="recent purchase",
timeframe="24 hours",
sender="Customer Service"
)

print(email)

Output:

Subject: Order Confirmation

Dear Mr. Smith,

Thank you for your recent purchase. We will process your request within 24 hours.

Best regards,
Customer Service

3. Configuration Files

String Templates are useful for processing configuration files:

python
# Content of a config template
config_template = """
DATABASE_URL = $db_url
API_KEY = $api_key
DEBUG = $debug_mode
LOG_PATH = $log_directory/app.log
"""

template = Template(config_template)
config = template.substitute(
db_url="postgresql://user:pass@localhost/mydb",
api_key="a1b2c3d4e5f6",
debug_mode="True",
log_directory="/var/log"
)

print("Generated configuration:")
print(config)

Output:

Generated configuration:

DATABASE_URL = postgresql://user:pass@localhost/mydb
API_KEY = a1b2c3d4e5f6
DEBUG = True
LOG_PATH = /var/log/app.log

Advanced Template Usage

Custom Template Delimiters

You can create your own template class with different delimiters:

python
from string import Template

# Create a custom template class
class CustomTemplate(Template):
# Change the delimiter from $ to %
delimiter = '%'

# Use the custom template
custom_template = CustomTemplate("Hello, %name! Today is %day.")
result = custom_template.substitute(name="David", day="Monday")
print(result)

Output:

Hello, David! Today is Monday.

Using Templates with Dictionaries

You can pass a dictionary of values to the template methods:

python
template = Template("$name ordered $item for $$price.")

data = {
"name": "Emma",
"item": "coffee",
"price": 3.99
}

result = template.substitute(data)
print(result)

Output:

Emma ordered coffee for $3.99.

Escaping the $ Character

To include a literal $ in your template, double it:

python
template = Template("The price is $$amount.")
result = template.substitute(amount=25)
print(result)

Output:

The price is $25.

String Templates vs. Other Formatting Methods

Let's compare string templates with other Python formatting options:

python
name = "Frank"
age = 30

# Using String Template
from string import Template
template = Template("$name is $age years old.")
template_result = template.substitute(name=name, age=age)

# Using f-string (Python 3.6+)
f_string_result = f"{name} is {age} years old."

# Using format() method
format_result = "{} is {} years old.".format(name, age)

# Using % formatting (older style)
percent_result = "%s is %d years old." % (name, age)

print(f"Template: {template_result}")
print(f"F-string: {f_string_result}")
print(f"format(): {format_result}")
print(f"% method: {percent_result}")

Output:

Template: Frank is 30 years old.
F-string: Frank is 30 years old.
format(): Frank is 30 years old.
% method: Frank is 30 years old.

When to Use String Templates

  • When dealing with user-supplied format strings (safer against code injection)
  • When working with templates that non-programmers might edit
  • For configuration files and externalized templates
  • When you need a simpler syntax for basic substitutions

When to Use Other Methods

  • F-strings: For inline formatting in Python 3.6+ code when performance matters
  • format(): For complex formatting needs or Python versions before 3.6
  • % operator: Generally avoided in new code but may appear in legacy code

Real-World Example: Report Generator

Here's a practical example of using String Templates to generate a report:

python
from string import Template
import datetime

# Report template
report_template = Template("""
# Sales Report: $period

## Summary
- Total Revenue: $$revenue
- Units Sold: $units
- Average Price: $$average

## Regional Breakdown
$regional_data

Generated on $date by $author
""")

# Data for the report
data = {
"period": "Q2 2023",
"revenue": "320,500.00",
"units": 1500,
"average": "213.67",
"date": datetime.datetime.now().strftime("%Y-%m-%d"),
"author": "Sales System",
"regional_data": """
- North: $120,300 (540 units)
- South: $95,200 (490 units)
- East: $58,000 (280 units)
- West: $47,000 (190 units)
"""
}

# Generate the report
report = report_template.substitute(data)
print(report)

Output:

# Sales Report: Q2 2023

## Summary
- Total Revenue: $320,500.00
- Units Sold: 1500
- Average Price: $213.67

## Regional Breakdown

- North: $120,300 (540 units)
- South: $95,200 (490 units)
- East: $58,000 (280 units)
- West: $47,000 (190 units)

Generated on 2023-07-10 by Sales System

Summary

Python String Templates provide a simple yet powerful way to format strings with placeholders. Their key advantages include:

  • Easy-to-understand syntax with $name placeholders
  • Better security for user-supplied format strings
  • Flexibility through methods like substitute() and safe_substitute()
  • The ability to customize templates by extending the Template class

While f-strings and the format() method offer more formatting options and are generally more efficient, String Templates excel in scenarios involving user input, configuration files, and externally stored templates.

Additional Resources and Exercises

Further Reading

Exercises

  1. Basic Template: Create a template for a greeting card that includes the recipient's name, occasion, and a custom message.

  2. Error Handling: Write a function that safely applies a template even when some values are missing.

  3. Custom Template Class: Create a custom template class that uses @ as a delimiter instead of $.

  4. Template from File: Read a template from a file and substitute values from user input.

  5. HTML Template: Create a simple HTML template for a webpage that includes title, header, content, and footer placeholders.

  6. Advanced: Build a simple template engine that can handle nested templates and loops.

By mastering String Templates, you'll add another valuable tool to your Python string formatting toolkit!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)