## Python String Interpolation with the Percent (%) Operator

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 and a float value:

>>> print("Mr. %s, the total is %.2f." % ("Jekyll", 15.53))
'Mr. Jekyll, the total is 15.33.'


Just like the %s is a placeholder for strings, %f is a placeholder for floating point numbers. The ".2" before the f is what indicates how many digits we want displayed after the decimal point.

These are just two simple examples of what is possible, and a lot more placeholder types are supported. Here is the full list of placeholder types in more detail:

##### %c

This placeholder represents a single character.

>>> print("The character after %c is %c." % ("B", "C"))
The character after B is C.


Providing more than a single character as the variable here will raise an exception.

##### %s

This placeholder uses string conversion via str() prior to formatting. So any value that can be converted to a string via str() can be used here.

>>> place = "New York"
>>> print("Welcome to %s!" % place)
Welcome to New York!


Here we only have a single element to be used in our string formatting, and thus we're not required to enclose the element in a tuple like the previous examples.

##### %i and %d

These placholders represent a signed decimal integer.

>>> year = 2019
>>> print("%i will be a perfect year." % year)
2019 will be a perfect year.


Since this placeholder expects a decimal, it will be converted to one if a floating point value is provided instead.

##### %u

This placeholder represents an unsigned decimal integer.

##### %o

This placeholder represents an octal integer.

>>> number = 15
>>> print("%i in octal is %o" % (number, number))
15 in octal is 17

##### %x

Represents a hexadecimal integer using lowercase letters (a-f).

>>> number = 15
>>> print("%i in hex is %02x" % (number, number))
15 in hex is 0f


By using the "02" prefix in our placeholder, we're telling Python to print a two-character hex string.

##### %X

Represents a hexadecimal integer using uppercase letters (A-F).

>>> number = 15
>>> print("%i in hex is %04X" % (number, number))
15 in hex is 000F


And like the previous example, by using the "04" prefix in our placeholder, we're telling Python to print a four-character hex string.

##### %e

Represents an exponential notation with a lowercase "e".

##### %E

Represents an exponential notation with an uppercase "e".

##### %f

Represents a floating point real number.

>>> price = 15.95
>>> print("the price is %.2f" % price)
the price is 15.95

##### %g

The shorter version of %f and %e.

##### %G

The shorter version of %f and %E.

The placeholders shown above allow you to format strings by specifying data types in your templates. However, these aren't the only features of the interpolation operator. In the next subsection we'll see how we can pad our strings with spaces using the % operator.

#### Aligning the Output

Up until now we've only shown how to format text strings by specifying simple placeholders. With the help of an additional numerical value, you can define the total space that shall be reserved on either side of a variable in the output string.

As an example the value of %10s reserves 10 characters, with the extra spacing on the left side of the placeholder, and a value of %-10s puts any extra space to the right of the placholder. The single padding character is a space, and cannot be changed.

>>> place = "London"
>>> print ("%10s is not a place in France" % place)  # Pad to the left
London is not a place in France
>>> print ("%-10s is not a place in France" % place) # Pad to the right
London     is not a place in France


Dealing with numbers works in the same way:

>>> print ("The postcode is %10d." % 25000)    # Padding on the left side
The postcode is      25000.
>>> print ("The postcode is %-10d." % 25000)   # Padding on the right side
The postcode is 25000     .


Truncating strings and rounding numbers is the counterpart to padding. Have a look at Rounding Numbers in Python in order to learn more about the traps that are hiding here.

### Conclusion

In this article we saw how the interpolation (aka formatting) operator is a powerful way to format strings, which allows you to specify data type, floating point precision, and even spacing/padding.

Berlin -- Genève -- Cape Town
IT developer, trainer, and author. Coauthor of the Debian Package Management Book (http://www.dpmb.org/).