Pretty Tables in Python

One of the challenges of using a text based programming language like Python is ensuring that information is printed in a user friendly format. This is usually not a problem when printing single variables but when we need to print multiple arrays that need to be well aligned with one another, we run into various formatting issues like the example below.

Let us consider this example of a shopping cart. Different items have been bought with various quantities and prices. This information is held in different dedicated arrays as shown below.

Data into these arrays can be accepted from the user via a loop. Let us assume all this information was entered by the user. So the code would look something like this:

When the arrays have gotten multiple items, printing them can take various forms. Using a loop that prints them next to one another like an actual supermarket bill might look something like this.

As it is evident the output looks pretty bad. Despite the best tab and space formatting it is unlikely there will be a perfect way to get a tabular structure to such an output. To deal with this issue, I began teaching (and using) Pretty Tables in Python.

You will find all the relevant installation and settings documentation for it here.

After successfully installing it, you import it into your Replit.

Next, set up the column headers for your table. Remember to use the same number of columns as there are arrays to be displayed.

That’s it! All we now have to do is add each row of information onto this table within the loop and print out the entire table object!

We can even add a total row at the end of this table to make it more user friendly to look at.

Student examples

My Computer Science students have found good success with using Pretty Tables in a wide range of scenarios. Couple of examples below.

Collecting and printing average temperatures for a week.

Managing and displaying a recipe book.

Other alternatives

I also learned of Text Table library in Python recently. It might be worth exploring that too. With the wide range of data that students generate when learning Python, user friendly options like these definitely help them realize that programming is indeed about converting data into information.