You may be surprised to know that there are many ways to format strings in Python. Before Python 3.6, there were two basic tools for interpolating (mixing) values, variables, and expressions within string literals — (1) The string interpolation operator (%) (the math’s modulo operator) and (2) The string.format() method. Python 3.6 introduced a new feature — “f-strings”. However, this article talks about a different string formatting method — string formatting with then help of Template class.
Formatting with String Template Class
Python Templates provide a flexible way to substitute data into strings. While other string substitution methods like f-strings and %
are common, the Template class offers a unique advantage: customizability. You can define your own rules for string interpolation
The string. Template class provides a simple way to perform string substitution. You can use $ to mark the beginning of a placeholder and then substitute values using the substitute() method.
What is a Template?
1 — In Python, a Template is a class of the string module which was introduced in Python 2.4 (library).
2 — It serves as an alternative to built-in substitution options (like %
) for creating complex string-based templates.