Open In App

String Template Class in Python

Last Updated : 15 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In the String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing $$ creates a single escaped $.
 

Python String Template:

The Python string Template is created by passing the template string to its constructor. It supports $-based substitutions. This class has 2 key methods: 

  • substitute(mapping, **kwds): This method performs substitutions using a dictionary with a process similar to key-based mapping objects. keyword arguments can also be used for the same purpose. In case the key-based mapping and the keyword arguments have the same key, it throws a TypeError. If keys are missing it returns a KeyError.
  • safe_substitute(mapping, **kwds): The behavior of this method is similar to that of the substitute method but it doesn’t throw a KeyError if a key is missing, rather it returns a placeholder in the result string. 
     

The substitute() method raises a KeyError when a placeholder is not supplied in a dictionary or a keyword argument. For mail-merge style applications, user-supplied data may be incomplete and the safe_substitute() method may be more appropriate — it will leave placeholders unchanged if data is missing:

Below are a few simple examples.
Example 1: 

Python3




# A Simple Python template example
from string import Template
  
# Create a template that has placeholder for value of x
t = Template('x is $x')
  
# Substitute value of x in above template
print (t.substitute({'x' : 1}))


Output:  

x is 1

Following is another example where we import names and marks of students from a list and print them using template.
Example 2: 

Python3




# A Python program to demonstrate the
# working of the string template
from string import Template
  
# List Student stores the name and marks of three students
Student = [('Ram',90), ('Ankit',78), ('Bob',92)]
  
# We are creating a basic structure to print the name and
# marks of the students.
t = Template('Hi $name, you have got $marks marks')
  
for i in Student:
     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

The below example shows the implementation of the safe_substitute method. 
Example 3: 

Python3




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


Output:  

Raju Kumar is the TCE of $company

Notice that we have not provided the “$company” placeholder any data, but it won’t throw an error, rather will return the placeholder as a string as discussed above. 

Printing the template String

The “template” attribute of the Template object can be used to return the template string as shown below: 
Example: 

Python3




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


Output: 

Template String = I am $name from $city 

Escaping $ Sign

The $$ can be used to escape $ and treat as part of the string. 
Example: 

Python3




template = Template('$$ is the symbol for $name')
string = template.substitute(name='Dollar')
print(string)


Output: 

$ is the symbol for Dollar 

The ${Identifier}

The ${Identifier} works similar to that of $Identifier. It comes in handy when valid identifier characters follow the placeholder but are not part of the placeholder. 
Example: 

Python3




template = Template( 'That $noun looks ${noun}y')
string = template.substitute(noun='Fish')
print(string)


Output:  

That Fish looks Fishy

Another application for the template is separating program logic from the details of multiple output formats. This makes it possible to substitute custom templates for XML files, plain text reports, and HTML web reports.
Note that there are other ways also to print formatted output like %d for integer, %f for float, etc (Refer this for details)
Reference: https://docs.python.org/3.3/tutorial/stdlib2.html 
 



Similar Reads

Placeholders in jinja2 Template - Python
Web pages use HTML for the things that users see or interact with. But how do we show things from an external source or a controlling programming language like Python? To achieve this templating engine like Jinja2 is used. Jinja2 is a templating engine in which placeholders in the template allow writing code similar to Python syntax which after pas
5 min read
Python | Document field detection using Template Matching
Template matching is an image processing technique which is used to find the location of small-parts/template of a large image. This technique is widely used for object detection projects, like product quality, vehicle tracking, robotics etc. In this article, we will learn how to use template matching for detecting the related fields in a document
2 min read
Python | Set Background Template in kivy
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Setting a good background template is a good thing to make your app look more attractive to the user. For insertin
2 min read
Template Method - Python Design Patterns
The Template method is a Behavioral Design Pattern that defines the skeleton of the operation and leaves the details to be implemented by the child class. Its subclasses can override the method implementations as per need but the invocation is to be in the same way as defined by an abstract class. It is one of the easiest among the Behavioral desig
4 min read
Implementing News Parser using Template Method Design Pattern in Python
While defining algorithms, programmers often neglect the importance of grouping the same methods of different algorithms. Normally, they define algorithms from start to end and repeat the same methods in every algorithm. This practice leads to code duplication and difficulties in code maintenance – even for a small logic change, the programmer has
4 min read
Python Pyramid - HTML Form Template
Pyramid is an open-source web application development framework written in Python. It is a flexible and modular framework that is used to build web applications from single-page to large, and complex websites. In this article, you will learn how to create the HTML Form in Python Pyramid. And How Pyramid reads data from HTML Form. Setting up the pro
4 min read
Python Falcon - Jinja2 Template
Python Falcon is a lightweight and minimalist web framework designed for building web APIs, with a particular emphasis on simplicity, speed, and efficiency. Falcon is developed to handle HTTP requests efficiently and is optimized for performance, making it a suitable choice for developers who prioritize building high-performance APIs. It aims to pr
6 min read
Template matching using OpenCV in Python
Template matching is a technique for finding areas of an image that are similar to a patch (template). A patch is a small image with certain features. The goal of template matching is to find the patch/template in an image. To find it, the user has to give two input images: Source Image (S) - The image to find the template in, and Template Image (T
6 min read
Switching From Other Template in Python Jinja
Jinja, a template engine, seamlessly combines the power of Python with HTML's structure. It enhances the development experience, making web applications more flexible. Jinja solves the challenge of cleanly integrating server-side logic (Python) with client-side presentation (HTML). It eliminates clutter, offering a more elegant and readable way to
4 min read
Building a Background PDF Generation App Using Python Celery and Template Data
In today's digital age, businesses often require the generation of PDF files with dynamic data for various purposes such as reports, invoices, or certificates. However, generating these PDF files synchronously within a web application can lead to performance issues and user experience degradation. To solve this, we can create a background app that
3 min read
Article Tags :
Practice Tags :