Skip to content

Python pretty print table | Example code

  • by

Use PrettyTable from prettytable module to pretty print table in Python. There are several ways to print tables in python, namely:

  • Using tabulate() function to print dict and lists
  • texttable
  • PrettyTable

Python pretty print table example

First, install a pretty table package then import module it into a project file.

from prettytable import PrettyTable

PTables = PrettyTable()

PTables = PrettyTable()
PTables.field_names = ["Selection No.", "Fruits", "Price"]
PTables.add_row(["0", "Apple", "1 $"])
PTables.add_row(["1", "Orange", "2.5 $"])
PTables.add_row(["2", "Grapes", "5 $"])
PTables.add_row(["3", "Cherry", "6 $"])
print(PTables)

Output:

Python pretty print table

Read more PrettyTable: https://pypi.python.org/pypi/PrettyTable

Another example

There are some light and useful python packages for this purpose:

tabulate

from tabulate import tabulate
print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
Name      Age
------  -----
Alice      24
Bob        19

texttable

from texttable import Texttable
t = Texttable()
t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]])
print(t.draw())
+-------+-----+
| Name  | Age |
+=======+=====+
| Alice | 24  |
+-------+-----+
| Bob   | 19  |
+-------+-----+

Do comment if you have any doubts or suggestions on this Python print table topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading