Output format specification

Here is an example that illustrates printing floating point numbers, strings, and integers with specified formatting:

Python 3.4.5 (default, Jun  1 2017, 13:52:39) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> seconds= 63
>>> name = "Frodo"
>>> pi = 3.1415926535
>>> print("seconds = {0:4d} name = {1:10s} pi = {2:5.2f} pi = {2:10.2e}".format(seconds, name, pi, pi))
seconds =   63 name = Frodo      pi =  3.14 pi =   3.14e+00

Let's see what is happening with the print statement here.

>>> print("seconds = {0:4d} name = {1:10s} pi = {2:5.2f} pi = {2:10.2e}".format(seconds, name, pi, pi))

The quotes indicate that we are printing a string. We see that the variables being printed are listed as arguments to the format() function. This function is appended to the string after a dot (period). The format function is called a “method” of the Python string. All Python strings come with this method.

We see that the string has four fields enclosed in curly braces {}. These fields mark places where the listed values are inserted. The braces enclose a code that has two parts separated by a colon as in n:fmt where n gives the list positional index of the value being substituted. That is, n = 0 specifies the first value seconds in the call to the format function. Similarly, n = 1 specifies the second value, name, etc. (The format code fmt is derived from the printf function in C.) Here is how it works:



Subsections