String Template Class in Python
Last Updated :
13 Jun, 2025
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}))
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]))
OutputHi 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)
OutputRaju 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)
OutputTemplate 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)
OutputThat 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.
Similar Reads
self in Python class In Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance. It is essential for accessing attributes and methods within the cla
6 min read
Using a Class with Input in Python In this article, we will see how to take input using class in Python. Using a Class with Input in Python It is to be noted that while using class in Python, the __init__() method is mandatory to be called for declaring the class data members, without which we cannot declare the instance variable (da
2 min read
Class or Static Variables in Python All objects share class or static variables. An instance or non-static variables are different for different objects (every object has a copy). For example, let a Computer Science Student be represented by a class CSStudent. The class may have a static variable whose value is "cse" for all objects.
9 min read
Get Variable Name As String In Python In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods
3 min read
Convert String to Set in Python There are multiple ways of converting a String to a Set in python, here are some of the methods.Using set()The easiest way of converting a string to a set is by using the set() function.Example 1 : Pythons = "Geeks" print(type(s)) print(s) # Convert String to Set set_s = set(s) print(type(set_s)) pr
1 min read