Member-only story
Methods of printing tables in Python that you don’t know
Written in front
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 Texttable
class. Then, create a Texttable
object 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.