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
python_string_formatting.htm
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy