Take control of your Python print() statements: part 3

In the last post, we learned how to control the precision of the number we print as well as the number of spaces these numbers take up. The last thing we need to learn to output nice data tables is how to align text and numbers when we use .format().

Aligning text and numbers with .format()

We previously learned to specify the number of spaces allocated to the inputs we provide to .format(). Now we will see that we can tell Python how we want to align our text or numbers in these spaces. We can left-adjust (<), right-adjust (>) and center (^) our values. Here is a brief example:

# Example 1
print('L {:<20} R'.format('x'))
# Example 2
print('L {:^20} R'.format('x'))
# Example 3
print('L {:>20} R'.format('x'))

The output of these examples is:

L x                    R
L          x           R
L                    x R

Pretty cool. We told Python to leave 20 spaces for the text we wanted to enter, and depending on the symbol we specified, we were able to change the justification of our text.

You can even specify the character you want to use instead of empty spaces.

print ('{:=<20}'.format('hello'))
print ('{:_^20}'.format('hello'))
print ('{:.>20}'.format('hello'))

The output of these example is:


As you can see, .format() has lots of options. Visit the string documentation or this useful site if you want to learn more.

Putting it all together

When working with data, we often want to have a quick look to make sure there are no mistakes and to see if any patterns are present. One way to do this is to plot your data. However, some types of data tend to be better presented in a nicely structured table.

For this example, we will work with some made-up data:

data = [['NAME', 'AGE', 'HANDEDNESS', 'SCORE (%)'],
        ['Martin', 38, 'L', 54.123],
        ['Marty', 33, 'L', 32.438],
        ['Martine', 25, 'R', 71.128],
        ['Martyn', 59, 'R', 50.472],
        ['Mart', 23, 'L', 2.438],
        ['Martyne', 15, 'R', 71.128],
        ['Marlyn', 101, 'R', 0.472],
        ['Marti', 2, 'L', 55.438],
        ['Mardi', 9, 'R', 81.128],
        ['Martyne', 49, 'R', 24.472],
        ['Marteen', 91, 'L', 1.128]]

Note that the first row of data (data[0]) contains the column labels. The other rows contain the data for each subject.

As you might suspect, running print(data) does not result in a nice output (try it to see for yourself!). A better solution is to apply what we have learned to generate a nice table. Here is the code:

dash = '-' * 40

for i in range(len(data)):
    if i == 0:

The output of this code look like this:

Martin      38     L              54.1
Marty       33     L              32.4
Martine     25     R              71.1
Martyn      59     R              50.5
Mart        23     L               2.4
Martyne     15     R              71.1
Marlyn     101     R               0.5
Marti        2     L              55.4
Mardi        9     R              81.1
Martyne     49     R              24.5
Marteen     91     L               1.1

In terms of the code, we first create a variable called dash that contains 40 dashes.

The code then looped over each of the 12 items in our data variable. If we are dealing with our first item (i.e., i = 0), we tell Python that we want to print a line of dashes, then print our headers, followed by another line of dashes. Notice how we specify the number of spaces we want for each header as well as the alignment of the text.

For all the other items in our data variable, we print the text and values using the same number of spaces used for the header, and specify whether we want to print integers (d), a strings (s) or floating point numbers (f). Note that because HANDEDNESS is such a long word, it looks better to center the text printed below it. Otherwise, the alignment is the same as for the header row.

Make sure you understand how this code works. To really consolidate your learning, try changing things in the print statements and see if it generates the expected outcome.


Hopefully you enjoyed these tutorials on the .format() string method and the print() function. Now you have no more excuses for ugly and uninformative print statements!



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s