Introduction to string templates
A string template acts as a sketch of how the final string should look. It is a pattern that is used as a basis for creating other strings. String templates usually includes tags or placeholders that represent a certain set of text that will be replaced with the appropriate value when the actual string is created.
Python offers some various tools for creating string templates some of which you might already be familiar with. They includes:
%-formatting:
This is a popular formatting style that uses the '%'
operator as a placeholder for variable values.
As you can see above, the % placeholders gets replaced with the actual values when using the template for creating a string.
str.format():
The str class defines the format()
method which takes the passed arguments, formats them, and places them in the string where the {}
placeholders are:
f-Strings (Formatted String Literals):
This is a relatively new string formatting method in Python (introduced in Python 3.6) that makes use of string literals prefixed with an ‘f’. F-strings provide a simple way to embed expressions inside of string literals.
The string.Template class
The Template
class available in the string
module enables the use of advanced and more expressive way of templating strings. It provides a powerful set of features for customizing how strings are templated, allowing us to perform complex substitutions and formatting operations.
The string
module is freely available in the standard library and we, therefore, just need to import it in our program without extra installations.
Basic Syntax
Constructing the template:
We start by creating an instance of the Template
class and passing in a string containing placeholders By convention we enclose the placeholders in curly braces ({}) in order tp distinguish them from other words in the template string.
Template(template)
template |
A required string that containing the necessary placeholders. |
**kwargs |
Any other necessary keyword arguments to be used in the formating such as delimiter |
By default, the Template class uses the dollar sign("$"
) character as the placeholder delimiter but we can change this as we will see later in Advanced templates
Substituting a value into the template
This is done by calling the substitute()
method on the template string, and passing in a dictionary with the desired values, or alternatively, passing the substitute values as keyword arguments.
The substitute()
method have the following syntax:
substitute(mapping={}, **kwargss)
Where, mapping
is an optional argument which is given if we are not passing the substitute values as keyword argument. Likewise, the **kwargs
arguments refers to the substitute values passes as keyword arguments if we are not passing them in the mapping dictionary.
A practical example
Safe Substitution
The substitute() method will raise a KeyError
exception if we do not provide any of the defined substitute values.
We can avoid the error with safe substitution using the safe_substitute()
method. This method replaces all placeholders in the template string, but will leave unknown placeholders intact. This makes it possible to use templates even when not all possible placeholders exist.
Get all the placeholder names
The get_identifiers()
method returns a list containing all the placeholder names used in the template string.
Advanced templates
The default way that the string.Template class works can be overridden by adjusting the the regex pattern that it uses to find the placeholder names in the template string. A direct way to achieve this is by simply changing the delimiter
and idpattern
class attributes.
In the above example, substitution rules are changed so that the delimiter is '@'
instead of the default '$'
and placeholder names must start with an underscore.
You can define more complex rules by setting an entirely new regular expressions as the idpattern
.