String Template Class in Python

String Template Class in Python

3 mins read435 Views Comment
Updated on Jan 9, 2023 12:47 IST

In this article, we will learn about the template class of string module that is used to format the string in Python with the help of different examples.

2023_01_MicrosoftTeams-image-115.jpg

The string module in python has a Template class that can be used to format strings in python. Python string templates are implemented by passing the constructor with a template string as an argument. In simpler terms python string template class allows us to create variable stings that can be updated with a value as per need.
Now that we are familiar with what it does let’s dive into how it works.

String Template Class Methods:

There are 3 key methods that can be used to create or format string from a string template. Let’s look into each one of them.

  • string.Template(template): This is a constructor within python’s string template class that accepts the string template as its argument.
  • substitute(mapping,**keywords): This method as the name suggest is used to map string values to their corresponding placeholders(template strings) in the string.  Here the mapping argument is used to map the string template to the string values. If a template string or its corresponding string value is missing, it raises keyError.
  • safe_substitue(mapping,**keywords): This function performs exactly like the above-discussed substitute() method, with the key difference being, it doesn’t raise a keyError even if a placeholder from either the template or string value is missing, instead it sets the original value as default for missing entities. It also 

Note: The $(Dollar) sign is used to define the placeholder in Template string formatting.

What is Programming What is Python
What is Data Science What is Machine Learning

Now let’s take a look at a couple of examples to better understand the concept.

Example: Using substitute method of Python Template string class.

 
# import Template from string module
from string import Template
# Create a template string object
# that acts as a placeholder
template_object = Template('$greetings! You are at $platform.')
# Substitute values of greetings and
# platform in above template object
# using substitute() method
formatted_string=template_object.substitute(
{'platform' : "Naukri E-learning",
'greetings':"Welcome"}
)
print(formatted_string)
Copy code

Output:

Welcome! You are at Naukri E-learning.

Example 2: Using the safe_substitute method of the Python Template string class.

 
# import Template from string module
from string import Template
# Create a template string object
# that acts as a placeholder
template_object = Template('$greetings! You are at $platform.')
# Substitute values of greetings and
# platform in above template object
# using safe_substitute() method
formatted_string=template_object.safe_substitute(
{'platform' : "Naukri E-learning",
'greetings':"Welcome"}
)
print(formatted_string)
Copy code

Output:

Welcome! You are at Naukri E-learning.

Example 3: Difference between substitute and safe _substitute methods.

 
# import Template from string module
from string import Template
# Create a template string object
# that acts as a placeholder
template_object = Template('$greetings! You are at $platform.')
# Substitute values of
# platform in above template object
# using safe_substitute() method
formatted_string_1=template_object.safe_substitute(
{'platform' : "Naukri E-learning"}
)
print(formatted_string_1)
# Substitute values of
# platform in above template object
# using substitute() method
formatted_string_2=template_object.substitute(
{'platform' : "Naukri E-learning"}
)
print(formatted_string_2)
Copy code

Output:

$greetings! You are at Naukri E-learning.
Traceback (most recent call last):
  File "0d655531-4f1f-4220-8f81-9ee563826234.py", line 21, in <module>
    {'platform' : "Naukri E-learning"}
  File "/usr/local/lib/python3.7/string.py", line 132, in substitute
    return self.pattern.sub(convert, self.template)
  File "/usr/local/lib/python3.7/string.py", line 125, in convert
    return str(mapping[named])
KeyError: 'greetings'

As you can observe in the above output, we have not provided the value of placeholder $greetings. In the case of safe_substitute() method, the placeholder is set to the template string itself as the default value and prints out the output, whereas in the case of the substitute () method, it raises a keyError.

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

Escaping the $ sign

There might be a situation wg=here you have the need to use the dollar sign without making it a placeholder and treat it as a string. In these types of situations, we make use of the $$ symbol. Take a look at the below example for reference.

Example 4: Escaping the $ symbol with $$.

 
# import Template from string module
from string import Template
# Create a template string object
# that acts as a placeholder
template_object = Template('The $ is the currency of $country.')
# Substitute values of
# platform in above template object
# using safe_substitute() method
formatted_string_1=template_object.safe_substitute(
{'country' : "USA"}
)
print(formatted_string_1)
Copy code
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio