What is a string template in Python?
A string template in Python is a way to perform string substitution using the Template
class from the string
module. It provides an alternative to the traditional string formatting methods (%
formatting, .format()
, and f-strings) by using a simpler and safer substitution mechanism, especially useful in scenarios requiring user-provided input.
Two types of substitute
methods
substitute(mapping, **kwds):
safe_substitute(mapping, **kwds):
Creating a string template
To create a string template in Python, you use the Template
class from the string
module. A string template is initialized with a string containing placeholders in the format $variable_name
or ${variable_name}
.
Steps to create a string template
Import the Template
class from the string
module.
Define a template string with placeholders.
Use .substitute()
or .safe_substitute()
to replace placeholders with values.
Creating and using a string template using substitute()
Here, we’ll dive into the substitute method using the code example given below.