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
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read