21. Formatted Output
In this chapter of our Python tutorial we will have a closer look at the various ways of creating nicer output in Python. We present all the different ways, but we recommend that you should use the format method of the string class, which you will find at end of the chapter. «string format» is by far the most flexible and Pythonic approach.
So far we have used the print function in two ways, when we had to print out more than two values:
The easiest way, but not the most elegant one:
We used print with a comma separated list of values to print out the results, as we can see in the following example. All the values are separated by blanks, which is the default behaviour. We can change the default value to an arbitrary string, if we assign this string to the keyword parameter «sep» of the print function:
q = 459 p = 0.098 print(q, p, p * q)
OUTPUT:
OUTPUT:
OUTPUT:
Alternatively, we can construe a new string out of the values by using the string concatenation operator:
print(str(q) + " " + str(p) + " " + str(p * q))
OUTPUT:
The second method is inferior to the first one in this example.
Enjoying this page? We offer live Python training courses covering the content of this site.
The Old Way or the non-existing printf and sprintf
Is there a printf in Python? A burning question for Python newbies coming from C, Perl, Bash or other programming languages who have this statement or function. To answer «Python has a print function and no printf function» is only one side of the coin or half of the truth. One can go as far as to say that this answer is not true. So there is a «printf» in Python? No, but the functionality of the «ancient» printf is contained in Python. To this purpose the modulo operator «%» is overloaded by the string class to perform string formatting. Therefore, it is often called string modulo (or somethimes even called modulus) operator, though it has not a lot in common with the actual modulo calculation on numbers. Another term for it is «string interpolation», because it interpolates various class types (like int, float and so on) into a formatted string. In many cases the string created via the string interpolation mechanism is used for outputting values in a special way. But it can also be used, for example, to create the right format to put the data into a database. Since Python 2.6 has been introduced, the string method format should be used instead of this old-style formatting. Unfortunately, string modulo «%» is still available in Python3 and what is even worse, it is still widely used. That’s why we cover it in great detail in this tutorial. You should be capable of understanding it, when you encounter it in some Python code. However, it is very likely that one day this old style of formatting will be removed from the language. So you should get used to str.format().
The following diagram depicts how the string modulo operator works:
On the left side of the «string modulo operator» there is the so-called format string and on the right side is a tuple with the content, which is interpolated in the format string. The values can be literals, variables or arbitrary arithmetic expressions.
The format string contains placeholders. There are two of those in our example: «%5d» and «%8.2f».
The general syntax for a format placeholder is
Let’s have a look at the placeholders in our example. The second one «%8.2f» is a format description for a float number. Like other placeholders, it is introduced with the «%» character. This is followed by the total number of digits the string should contain. This number includes the decimal point and all the digits, i.e. before and after the decimal point. Our float number 59.058 has to be formatted with 8 characters. The decimal part of the number or the precision is set to 2, i.e. the number following the «.» in our placeholder. Finally, the last character «f» of our placeholder stands for «float».
If you look at the output, you will notice that the 3 decimal digits have been rounded. Furthermore, the number has been preceded in the output with 3 leading blanks.
The first placeholder «%5d» is used for the first component of our tuple, i.e. the integer 453. The number will be printed with 5 characters. As 453 consists only of 3 digits, the output is padded with 2 leading blanks. You may have expected a «%5i» instead of «%5d». Where is the difference? It’s easy: There is no difference between «d» and «i» both are used for formatting integers. The advantage or beauty of a formatted output can only be seen, if more than one line is printed with the same pattern. In the following picture you can see, how it looks, if five float numbers are printed with the placeholder «%6.2f» in subsequent lines:
Conversion | Meaning |
---|---|
d | Signed integer decimal. |
i | Signed integer decimal. |
o | Unsigned octal. |
u | Obsolete and equivalent to ‘d’, i.e. signed integer decimal. |
x | Unsigned hexadecimal (lowercase). |
X | Unsigned hexadecimal (uppercase). |
e | Floating point exponential format (lowercase). |
E | Floating point exponential format (uppercase). |
f | Floating point decimal format. |
F | Floating point decimal format. |
g | Same as «e» if exponent is greater than -4 or less than precision, «f» otherwise. |
G | Same as «E» if exponent is greater than -4 or less than precision, «F» otherwise. |
c | Single character (accepts integer or single character string). |
r | String (converts any python object using repr()). |
s | String (converts any python object using str()). |
% | No argument is converted, results in a «%» character in the result. |
The following examples show some example cases of the conversion rules from the table above:
String Formatting
Python uses C-style string formatting to create new, formatted strings. The «%» operator is used to format a set of variables enclosed in a «tuple» (a fixed size list), together with a format string, which contains normal text together with «argument specifiers», special symbols like «%s» and «%d».
Let’s say you have a variable called «name» with your user name in it, and you would then like to print(out a greeting to that user.)
# This prints out "Hello, John!" name = "John" print("Hello, %s!" % name)
To use two or more argument specifiers, use a tuple (parentheses):
# This prints out "John is 23 years old." name = "John" age = 23 print("%s is %d years old." % (name, age))
Any object which is not a string can be formatted using the %s operator as well. The string which returns from the «repr» method of that object is formatted as the string. For example:
# This prints out: A list: [1, 2, 3] mylist = [1,2,3] print("A list: %s" % mylist)
Here are some basic argument specifiers you should know:
%s — String (or any object with a string representation, like numbers)
%f — Floating point numbers
%.f — Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X — Integers in hex representation (lowercase/uppercase)
Exercise
You will need to write a format string which prints out the data using the following syntax: Hello John Doe. Your current balance is $53.44.
data = («John», «Doe», 53.44) format_string = «Hello» print(format_string % data) data = («John», «Doe», 53.44) format_string = «Hello %s %s. Your current balance is $%s.» print(format_string % data) #test_output_contains(«Hello John Doe. Your current balance is $53.44.», no_output_msg= «Make sure you add the `%s` in the correct spaces to the `format_string` to meeet the exercise goals!») test_object(‘format_string’) success_msg(‘Great work!’)
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
Ready to take the test? Head onto LearnX and get your Python Certification!