Formatting Strings with the Python Template Class

python_tutorials

Introduction

Python Templates are used to substitute data into strings. With Templates, we gain a heavily customizable interface for string substitution (or string interpolation).

Python already offers many ways to substitute strings, including the recently introduced f-Strings. While it is less common to substitute strings with Templates, its power lies in how we can customize our string formatting rules.

In this article, we’ll format strings with Python’s Template class. We’ll then have a look at how we can change the way our Templates can substitute data into strings.

For a better understanding of these topics, you’ll require some basic knowledge on how to work with classes and regular expressions.

Understanding the Python Template Class

The Python Template class was added to the string module since Python 2.4. This class is intended to be used as an alternative to the built-in substitution options (mainly to %) for creating complex string-based templates and for handling them in a user-friendly way.

The class’s implementation uses regular expressions to match a general pattern of valid template strings. A valid template string, or placeholder, consists of two parts: