Member-only story

Methods of printing tables in Python that you don’t know

Written in front

Beck Moulton
3 min readAug 24, 2024

In Python programming, we often need to print something at the end point. We know the formatting printing method and the useful f-string, but how to print a table elegantly? Like the following data.

headers = ['', '', '']fruits = [
['', 4, ''],
['', 5, ''],
['', 6, ''],
['', 7, ''],
]

How to print it to the end point like a table? You may think of using hardcoding to print line by line, but there are already ready-made wheels available. Let’s explore the implementation method below.

Hardcoding implementation of table printing

headers = ['', '', '']fruits = [
['', 4, ''],
['', 5, ''],
['', 6, ''],
['', 7, ''],
]#
print('|'.join(headers))#
print('-' * (len(headers) * 10))#
for fruit in fruits:
print('|'.join(str(item) for item in fruit))

Running the above code will output the following table:

||
-----+

In this example, we first import the Texttableclass. Then, create a Texttableobject and use the set_cols_align ()method to set the column alignment ('l' for left alignment, 'r' for right alignment, and'c 'for center alignment). Next, use the header ()method to set the header, and use the add_rows ()method to add data row by row. Finally, use the draw ()method to generate a string representation of the table, and use the print ()function to print it out.

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet