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.
% 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:
"Mr. %s, the total is %.2f." % ("Jekyll", 15.53)) 'Mr. Jekyll, the total is 15.33.'print(
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:
This placeholder represents a single character.
"The character after %c is %c." % ("B", "C")) The character after B is C.print(
Providing more than a single character as the variable here will raise an exception.
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.
"New York" print("Welcome to %s!" % place) Welcome to New York!place =
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.
2019 print("%i will be a perfect year." % year) 2019 will be a perfect year.year =
Since this placeholder expects a decimal, it will be converted to one if a floating point value is provided instead.
This placeholder represents an unsigned decimal integer.
This placeholder represents an octal integer.
15 print("%i in octal is %o" % (number, number)) 15 in octal is 17number =
Represents a hexadecimal integer using lowercase letters (a-f).
15 print("%i in hex is %02x" % (number, number)) 15 in hex is 0fnumber =
By using the "02" prefix in our placeholder, we're telling Python to print a two-character hex string.
Represents a hexadecimal integer using uppercase letters (A-F).
15 print("%i in hex is %04X" % (number, number)) 15 in hex is 000Fnumber =
And like the previous example, by using the "04" prefix in our placeholder, we're telling Python to print a four-character hex string.
Represents an exponential notation with a lowercase "e".
Represents an exponential notation with an uppercase "e".
Represents a floating point real number.
15.95 print("the price is %.2f" % price) the price is 15.95price =
The shorter version of
The shorter version of
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
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.
"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 Franceplace =
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.
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.