Open In App

String Template Class in Python

Last Updated : 13 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

String Template class from Python’s string module provides a simple, $-based way to perform string substitutions. It’s ideal for user-facing text, email templates and config files. Unlike str.format() or f-strings, it supports safe substitutions (missing keys won’t cause errors) and makes escaping $ symbols easy.

How Template Placeholders Work

Let’s see how placeholders are written in a template string.

  • Placeholders are marked by a $ followed by a valid Python identifier:

$name

  • To avoid confusion when placeholders are followed immediately by text, use curly braces:

${name}y

  • To include a literal dollar sign in your output, use two dollar signs:

$$

Creating a template

You create a template by passing the template string to Template():

Python
from string import Template
t = Template('Hello $name')

Key Methods of Template class

Template class provides two main methods to replace placeholders with actual values. These methods help you control how missing data is handled during substitution.

1. substitute(mapping, **kwds): This method replaces placeholders in the template with values you provide through a dictionary or keyword arguments. If a placeholder is missing a value, it raises a KeyError, so all placeholders must be supplied.

2. safe_substitute(mapping, **kwds): This method works like substitute, but if a placeholder value is missing, it leaves the placeholder unchanged instead of raising an error. This is useful when you want to avoid your program crashing due to incomplete data.

Examples

Example 1: In this example, we substitute a single value in the template.

Python
from string import Template
t = Template('x is $x')
print(t.substitute({'x': 1}))

Output
x is 1

Explanation: This code creates a template with the string 'x is $x', where $x is a placeholder. Using the substitute method with {'x': 1}, it replaces $x with 1.

Example 2: In this example, we loop through a list of students and print their marks using Template substitution.

Python
from string import Template
a = [('Ram', 90), ('Ankit', 78), ('Bob', 92)]
t = Template('Hi $name, you have got $marks marks')

for i in a:
    print(t.substitute(name=i[0], marks=i[1]))

Output
Hi Ram, you have got 90 marks
Hi Ankit, you have got 78 marks
Hi Bob, you have got 92 marks

Explanation: This code creates a template with placeholders $name and $marks. It loops through a list of student tuples, replacing the placeholders with each student's name and marks using substitute.

Example 3: In this example, we use safe_substitute to avoid errors when some placeholders have no corresponding value.

Python
from string import Template
t = Template('$name is the $job of $company')
s = t.safe_substitute(name='Raju Kumar', job='TCE')
print(s)

Output
Raju Kumar is the TCE of $company

Explanation: This code creates a template with placeholders $name, $job and $company. Using safe_substitute, it replaces $name and $job but leaves $company unchanged because no value is provided.

Printing the template string

You can easily access the original template string using the .template attribute of the Template object. This is useful when you want to display or inspect the template text itself.

Python
from string import Template
t = Template('I am $name from $city')
print('Template String =', t.template)

Output
Template String = I am $name from $city

Explanation: This code creates a template with placeholders $name and $city, then prints the original template string using the .template attribute without performing any substitutions.

Escaping the Dollar Sign $

Since $ is used to mark placeholders, you must use $$ if you want a literal dollar sign $ in your output. The Template class will replace $$ with a single $ when rendering the final string.

Python
from string import Template
t = Template('$$ is the symbol for $name')
s = t.substitute(name='Dollar')
print(s)

Output
$ is the symbol for Dollar

Explanation: This code creates a template where $$ represents a literal dollar sign and $name is a placeholder. Using substitute, it replaces $name with 'Dollar'.

Using ${Identifier}

When a placeholder is immediately followed by text (such as letters or numbers), you can use ${identifier} to clearly define where the placeholder ends. This avoids ambiguity and ensures correct substitution in your template.

Python
from string import Template
t = Template('That $noun looks ${noun}y')
s = t.substitute(noun='Fish')
print(s)

Output
That Fish looks Fishy

Explanation: This code creates a template with two placeholders: $noun and ${noun}. Using substitute, it replaces both with the value 'Fish'. The ${noun}y syntax ensures the placeholder ends before the letter y.


Next Article
Article Tags :
Practice Tags :

Similar Reads