Python String Interpolation with the Percent (%) Operator

python_tutorials

There are a number of different ways to format strings in Python, one of which is done using the % operator, which is known as the string formatting (or interpolation) operator. In this article we’ll show you how to use this operator to construct strings with a template string and variables containing your data.

The % Operator

This way of working with text has been shipped with Python since the beginning, and it’s also known as C-style formatting, as it originates from the C programming language. Another description for it is simple positional formatting.

The % operator tells the Python interpreter to format a string using a given set of variables, enclosed in a tuple, following the operator. A very simple example of this is as follows:

'%s is smaller than %s' % ('one', 'two')

The Python interpreter substitutes the first occurrence of %s in the string by the given string “one”, and the second %s by the string “two”. These %s strings are actually placeholders in our “template” string, and they indicate that strings will be placed there.

As a first example, below we demonstrate using the Python REPL how to print a string value

To finish reading, please visit source site