Python - String Template Class
Python's standard library has string module. It provides functionalities to perform different string operations.
String Template Class
The Template class in string module provides an alternative method to format the strings dynamically. One of the benefits of Template class is to be able to customize the formatting rules.
The implementation of Template uses regular expressions to match a general pattern of valid template strings. A valid template string, or placeholder, consists of two parts: The $ symbol followed by a valid Python identifier.
You need to create an object of Template class and use the template string as an argument to the constructor.
Next call the substitute() method of Template class. It puts the values provided as the parameters in place of template strings.
String Template Class Example
from string import Template temp_str = "My name is $name and I am $age years old" tempobj = Template(temp_str) ret = tempobj.substitute(name='Rajesh', age=23) print (ret)
It will produce the following output −
My name is Rajesh and I am 23 years old
Unpacking Dictionary Key-Value Pairs
We can also unpack the key-value pairs from a dictionary to substitute the values.
Example
from string import Template
student = {'name':'Rajesh', 'age':23}
temp_str = "My name is $name and I am $age years old"
tempobj = Template(temp_str)
ret = tempobj.substitute(**student)
print (ret)
It will produce the following output −
My name is Rajesh and I am 23 years old