Python tabulate – Print tabular data in Python

In this post we will be creating a Python script that will print tabular data to output, to do this we will be using the amazing ‘tabulate’ library which pretty-prints data to output. Its functions can be especially useful when outputting tables and wanting its contents to be in a user friendly and readable format.

To install the library run the following command.

pip install tabulate

See the snippet of Python code below where we utilise the tabulate library to print data.

from tabulate import tabulate
print(tabulate([['Harry', 'Potter'], ['Ron', 'Weasley']],
               headers=['Fistname', 'Lastname']))

The above would return the following to output.

Fistname    Lastname
----------  ----------
Harry       Potter
Ron         Weasley
>>> 

The tabulate library comes with a set of different table formats enabling us to change the aesthetics of our output, see the below where we apply one of the formats to our table.

from tabulate import tabulate
print(tabulate([['Harry', 'Potter'], ['Ron', 'Weasley']],
               headers=['Fistname', 'Lastname'],
               tablefmt='orgtbl'))

The above would return the following to output.

| Fistname   | Lastname   |
|------------+------------|
| Harry      | Potter     |
| Ron        | Weasley    |
>>> 

For a full list of table formats available click here.

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply