Python prettytable – Print tabulated data

In this post we will be creating a Python script that will print tabulated data to output. To do this we will be using the ‘prettytable‘ library, used for displaying tabular data in a visually appealing format.

To install the prettytable library run the following command.

pip install prettytable

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

from prettytable import PrettyTable

t = PrettyTable(['Firstname', 'Lastname'])
t.add_row(['Harry', 'Potter'])
t.add_row(['Ron', 'Weasley'])

print(t)

The above would return the following as output.

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

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

Leave a Reply