Displaying your data on the console in the form of a formatted table can be useful in many cases. It makes it easy to look at the data. In this post, I will discuss different modules that can help you accomplish the job.
PrettyTable
Installation
pip install PrettyTable
Documentation
https://ptable.readthedocs.io/en/latest/tutorial.html
Usage
Import PrettyTable from the prettytable module and create a new table. Then, you can use the add_row function to add a new row to the table.
from prettytable import PrettyTable my_table = PrettyTable() my_table.add_row([1, "Bob", 6, 11]) my_table.add_row([2, "Freddy", 4, 10]) my_table.add_row([3, "John", 7, 13]) print(my_table)
Output:
+---------+---------+---------+---------+
| Field 1 | Field 2 | Field 3 | Field 4 |
+---------+---------+---------+---------+
| 1 | Bob | 6 | 11 |
| 2 | Freddy | 4 | 10 |
| 3 | John | 7 | 13 |
+---------+---------+---------+---------+
The fields are marked as Field 1, Field 2, and so on. If you want custom field names, you can use field_names to achieve that.
from prettytable import PrettyTable my_table = PrettyTable() my_table.field_names = ["No.", "Name", "Grade", "Age"] my_table.add_row([1, "Bob", 6, 11]) my_table.add_row([2, "Freddy", 4, 10]) my_table.add_row([3, "John", 7, 13]) print(my_table)
Output:
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+-----+--------+-------+-----+
| 1 | Bob | 6 | 11 |
| 2 | Freddy | 4 | 10 |
| 3 | John | 7 | 13 |
+-----+--------+-------+-----+
Sort the rows of Table
Pretty Table also provides the feature to sort the data with respect to a particular field. For example, if we wanted to sort people by their age in the above table, we could use the sortby option.
from prettytable import PrettyTable my_table = PrettyTable() my_table.field_names = ["No.", "Name", "Grade", "Age"] my_table.add_row([1, "Bob", 6, 11]) my_table.add_row([2, "Freddy", 4, 10]) my_table.add_row([3, "John", 7, 13]) my_table.sortby = 'Age' print(my_table)
Output:
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+-----+--------+-------+-----+
| 2 | Freddy | 4 | 10 |
| 1 | Bob | 6 | 11 |
| 3 | John | 7 | 13 |
+-----+--------+-------+-----+
The data is sorted in ascending order. If it is required to sort the data in descending order, the reversesort option can be used.
from prettytable import PrettyTable my_table = PrettyTable() my_table.field_names = ["No.", "Name", "Grade", "Age"] my_table.add_row([1, "Bob", 6, 11]) my_table.add_row([2, "Freddy", 4, 10]) my_table.add_row([3, "John", 7, 13]) my_table.sortby = 'Age' my_table.reversesort = True print(my_table)
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+-----+--------+-------+-----+
| 3 | John | 7 | 13 |
| 1 | Bob | 6 | 11 |
| 2 | Freddy | 4 | 10 |
+-----+--------+-------+-----+
Delete the rows of Table
The function del_row can be used to delete a row from the table. It takes the row number as the parameter.
from prettytable import PrettyTable my_table = PrettyTable() my_table.field_names = ["No.", "Name", "Grade", "Age"] my_table.add_row([1, "Bob", 6, 11]) my_table.add_row([2, "Freddy", 4, 10]) my_table.add_row([3, "John", 7, 13]) my_table.del_row(1) print(my_table)
+-----+------+-------+-----+
| No. | Name | Grade | Age |
+-----+------+-------+-----+
| 1 | Bob | 6 | 11 |
| 3 | John | 7 | 13 |
+-----+------+-------+-----+
Clear All Data
All the data can be cleared by using the function clear_rows.
from prettytable import PrettyTable my_table = PrettyTable() my_table.field_names = ["No.", "Name", "Grade", "Age"] my_table.add_row([1, "Bob", 6, 11]) my_table.add_row([2, "Freddy", 4, 10]) my_table.add_row([3, "John", 7, 13]) my_table.clear_rows() print(my_table)
+-----+------+-------+-----+
| No. | Name | Grade | Age |
+-----+------+-------+-----+
+-----+------+-------+-----+
TextTable
Installation
pip install texttable
Documentation
https://texttables.readthedocs.io/en/latest/
https://pypi.org/project/texttable/
Usage
When I started reading the Python Package Index Page for this module, I immediately realized that this one is more advanced than the others.
Let’s start with a very simple usage example. Print a simple table.
from texttable import Texttable table = Texttable() table.header(["No.", "Name", "Grade", "Age"]) table.add_row([1, "Bob", 6, 11]) table.add_row([2, "Freddy", 4, 10]) table.add_row([3, "John", 7, 13]) print(table.draw())
Result
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+=====+========+=======+=====+
| 1 | Bob | 6 | 11 |
+-----+--------+-------+-----+
| 2 | Freddy | 4 | 10 |
+-----+--------+-------+-----+
| 3 | John | 7 | 13 |
+-----+--------+-------+-----+
Add all Rows at once
from texttable import Texttable table = Texttable() table.add_rows( [ ["No.", "Name", "Grade", "Age"], [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] ) print(table.draw())
Result
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+=====+========+=======+=====+
| 1 | Bob | 6 | 11 |
+-----+--------+-------+-----+
| 2 | Freddy | 4 | 10 |
+-----+--------+-------+-----+
| 3 | John | 7 | 13 |
+-----+--------+-------+-----+
Now let’s talk about the advanced features which let you better format your data.
Set Alignment of the Columns
You can set the alignment of the columns using the set_cols_align function. It takes a list as a parameter in which ‘l’ means left align and ‘r’ means right align.
from texttable import Texttable table = Texttable() table.add_rows( [ ["No.", "Name", "Grade", "Age"], [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] ) table.set_cols_align(['l', 'l', 'r', 'r']) print(table.draw())
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+=====+========+=======+=====+
| 1 | Bob | 6 | 11 |
+-----+--------+-------+-----+
| 2 | Freddy | 4 | 10 |
+-----+--------+-------+-----+
| 3 | John | 7 | 13 |
+-----+--------+-------+-----+
Set the data type
We can also set the data types of the columns using the set_cols_dtype function. Please note that the data type must be set before setting the data.
from texttable import Texttable table = Texttable() table.set_cols_dtype(['i', 't', 'f', 'e', 'a']) table.add_rows( [ ["No.", "Name", "Percentage", "exp", "auto"], [1, "Bob", 75.36, 25000, "text"], [2.0, "Freddy", 95.3, 0.036, 53], [3.1, "John", 67.15, 13, 0.0000000056], ] ) print(table.draw())
Here ‘i’ means integer, ‘t’ means text, and so on. The output of the code is:
+-----+--------+------------+-----------+-------+
| No. | Name | Percentage | exp | auto |
+=====+========+============+===========+=======+
| 1 | Bob | 75.360 | 2.500e+04 | text |
+-----+--------+------------+-----------+-------+
| 2 | Freddy | 95.300 | 3.600e-02 | 53 |
+-----+--------+------------+-----------+-------+
| 3 | John | 67.150 | 1.300e+01 | 0.000 |
+-----+--------+------------+-----------+-------+
Here is a list of different data types that you can set.
a | automatic (try to use the most appropriate datatype) |
t | treat as text |
f | treat as float in decimal format |
e | treat as float in exponential format |
i | treat as int |
Vertical Alignment of Columns
You can also set the vertical alignment of the columns in case any row contains more than one line of info. You will set ‘t’ for top, ‘m’ for middle and ‘b’ for bottom.
from texttable import Texttable table = Texttable() table.set_cols_dtype(['i', 't', 'f', 'e', 'a']) table.set_cols_valign(['m', 'm', 't', 'b', 'm']) table.add_rows( [ ["No.", "Name", "Top", "Bottom", "Middle"], [1, "Dr.\nBob\nAlice", 75.36, 25000, "text"], [2.0, "Mr.\nFreddy\nJ.", 95.3, 0.036, 53], [3.1, "John\nA.", 67.15, 13, 0.0000000056], ] ) print(table.draw())
+-----+--------+--------+-----------+--------+
| No. | Name | Top | Bottom | Middle |
+=====+========+========+===========+========+
| | Dr. | 75.360 | | |
| 1 | Bob | | | text |
| | Alice | | 2.500e+04 | |
+-----+--------+--------+-----------+--------+
| | Mr. | 95.300 | | |
| 2 | Freddy | | | 53 |
| | J. | | 3.600e-02 | |
+-----+--------+--------+-----------+--------+
| 3 | John | 67.150 | | 0.000 |
| | A. | | 1.300e+01 | |
+-----+--------+--------+-----------+--------+
Set decoration type
You can use the set_deco function to set the decoration of the table. The following options are available.
Texttable.BORDER | Border around the table |
Texttable.HEADER | Horizontal line below the header |
Texttable.HLINES | Horizontal lines between rows |
Texttable.VLINES | Vertical lines between columns |
All of these options are enabled by default. Let’s see how to use them by an example
from texttable import Texttable table = Texttable() table.add_rows( [ ["No.", "Name", "Grade", "Age"], [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] ) table.set_deco(Texttable.HEADER) print(table.draw())
No. Name Grade Age
==========================
1 Bob 6 11
2 Freddy 4 10
3 John 7 13
To use more than one option, use the | operator.
from texttable import Texttable table = Texttable() table.add_rows( [ ["No.", "Name", "Grade", "Age"], [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] ) table.set_deco(Texttable.HEADER | Texttable.BORDER) print(table.draw())
+----------------------------+
| No. Name Grade Age |
+============================+
| 1 Bob 6 11 |
| 2 Freddy 4 10 |
| 3 John 7 13 |
+----------------------------+
TextTable is my favorite module so far
BeautifulTable
Installation
pip install beautifultable
Documentation
https://beautifultable.readthedocs.io/en/latest/
Usage
Following is the code for a simple table with a header:
from beautifultable import BeautifulTable my_table = BeautifulTable() my_table.column_headers = ["No.", "Name", "Grade", "Age"] my_table.append_row([1, "Bob", 6, 11]) my_table.append_row([2, "Freddy", 4, 10]) my_table.append_row([3, "John", 7, 13]) print(my_table)
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+-----+--------+-------+-----+
| 1 | Bob | 6 | 11 |
+-----+--------+-------+-----+
| 2 | Freddy | 4 | 10 |
+-----+--------+-------+-----+
| 3 | John | 7 | 13 |
+-----+--------+-------+-----+
Sort the rows of the Table
You can sort the rows of the table based on a column’s values. For example, to sort the table by age:
from beautifultable import BeautifulTable my_table = BeautifulTable() my_table.column_headers = ["No.", "Name", "Grade", "Age"] my_table.append_row([1, "Bob", 6, 11]) my_table.append_row([2, "Freddy", 4, 10]) my_table.append_row([3, "John", 7, 13]) my_table.sort('Age') print(my_table)
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+-----+--------+-------+-----+
| 2 | Freddy | 4 | 10 |
+-----+--------+-------+-----+
| 1 | Bob | 6 | 11 |
+-----+--------+-------+-----+
| 3 | John | 7 | 13 |
+-----+--------+-------+-----+
To sort in descending order, use reverse=True
from beautifultable import BeautifulTable my_table = BeautifulTable() my_table.column_headers = ["No.", "Name", "Grade", "Age"] my_table.append_row([1, "Bob", 6, 11]) my_table.append_row([2, "Freddy", 4, 10]) my_table.append_row([3, "John", 7, 13]) my_table.sort('Age', reverse=True) print(my_table)
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+-----+--------+-------+-----+
| 3 | John | 7 | 13 |
+-----+--------+-------+-----+
| 1 | Bob | 6 | 11 |
+-----+--------+-------+-----+
| 2 | Freddy | 4 | 10 |
+-----+--------+-------+-----+
Insert a Column
Use the insert_column function to insert a column at a particular position
from beautifultable import BeautifulTable my_table = BeautifulTable() my_table.column_headers = ["No.", "Name", "Grade", "Age"] my_table.append_row([1, "Bob", 6, 11]) my_table.append_row([2, "Freddy", 4, 10]) my_table.append_row([3, "John", 7, 13]) my_table.insert_column(2, "Marks", [95, 63, 82]) print(my_table)
+-----+--------+-------+-------+-----+
| No. | Name | Marks | Grade | Age |
+-----+--------+-------+-------+-----+
| 1 | Bob | 95 | 6 | 11 |
+-----+--------+-------+-------+-----+
| 2 | Freddy | 63 | 4 | 10 |
+-----+--------+-------+-------+-----+
| 3 | John | 82 | 7 | 13 |
+-----+--------+-------+-------+-----+
To insert the column at the end, the append_column function can be used.
from beautifultable import BeautifulTable my_table = BeautifulTable() my_table.column_headers = ["No.", "Name", "Grade", "Age"] my_table.append_row([1, "Bob", 6, 11]) my_table.append_row([2, "Freddy", 4, 10]) my_table.append_row([3, "John", 7, 13]) my_table.append_column("Marks", [95, 63, 82]) print(my_table)
+-----+--------+-------+-----+-------+
| No. | Name | Grade | Age | Marks |
+-----+--------+-------+-----+-------+
| 1 | Bob | 6 | 11 | 95 |
+-----+--------+-------+-----+-------+
| 2 | Freddy | 4 | 10 | 63 |
+-----+--------+-------+-----+-------+
| 3 | John | 7 | 13 | 82 |
+-----+--------+-------+-----+-------+
Delete a Row or Column
You can use the pop_column or pop_row function to remove a column or a row respectively.
from beautifultable import BeautifulTable my_table = BeautifulTable() my_table.column_headers = ["No.", "Name", "Grade", "Age"] my_table.append_row([1, "Bob", 6, 11]) my_table.append_row([2, "Freddy", 4, 10]) my_table.append_row([3, "John", 7, 13]) my_table.pop_column(2) print(my_table)
The column at the index 2 is removed as a result of the code on line 11
+-----+--------+-----+
| No. | Name | Age |
+-----+--------+-----+
| 1 | Bob | 11 |
+-----+--------+-----+
| 2 | Freddy | 10 |
+-----+--------+-----+
| 3 | John | 13 |
+-----+--------+-----+
Tabulate
Installation
pip install tabulate
Documentation
https://pyhdust.readthedocs.io/en/latest/tabulate.html
Usage
Import tabulate function from module tabulate. This function takes nested iterable objects like List or Tuple and makes columns on the basis of the comma. Our Example has a List as a parameter for Tabulate.
from tabulate import tabulate Table = [["Alice", 20], ["bob", 14], ["Jon",30]] print(tabulate(Table))
----- --
Alice 20
bob 14
Jon 12
----- --
One additional parameter of headers = “firstrow” makes first line header.
from tabulate import tabulate Table = [["name", "age"], ["Alice", 20], ["bob", 14], ["Jon", 12]] print(tabulate(Table, headers=("firstrow")))
name age
------ -----
Alice 20
bob 14
Jon 12
if the number of headers is less as compared to the number of columns in the table then the header pointing towards the last column and leaves the first one.
from tabulate import tabulate Table = [["name", "age"], [1, "Alice", 20], [2, "bob", 14], [3, "Jon", 12]] print(tabulate(Table, headers=("firstrow")))
name age
-- ------ -----
1 Alice 20
2 bob 14
3 Jon 12
In the Table if at any point if the value is missing missingval=”-” parameter print – or whatever the character or number on your own choice into the empty space.
from tabulate import tabulate Table = [["name", "age"], [1, "Alice", 20], [2, "bob", ], [3, "Jon", 12]] print(tabulate(Table, headers=("firstrow"), missingval="-"))
name age
-- ------ -----
1 Alice 20
2 bob -
3 Jon 12
Print table with grids
For formatting table with grids pass a parameter tablefmt = “grid”.
from tabulate import tabulate Table = [["No.", "name", "age"], [1, "Alice", 20], [2, "bob", ], [3, "Jon", 12]] print(tabulate(Table, headers="firstrow",missingval="-", tablefmt="grid"))
+-------+--------+-------+
| No. | name | age |
+=======+========+=======+
| 1 | Alice | 20 |
+-------+--------+-------+
| 2 | bob | - |
+-------+--------+-------+
| 3 | Jon | 12 |
+-------+--------+-------+
To make grid more fancy use tablefmt = “fancy_grid” or “rst” . Try it yourself.
Latex Formatting
tabulate function also print table in the Latex format. To print in this format pass parameter tablefmt = “latex” to function.
from tabulate import tabulate Table = [["No.", "name", "age"], [1, "Alice", 20], [2, "bob", ], [3, "Jon", 12]] print(tabulate(Table, headers="firstrow",missingval="-", tablefmt="latex"))
\begin{tabular}{rlr}
\hline
No. & name & age \\
\hline
1 & Alice & 20 \\
2 & bob & - \\
3 & Jon & 12 \\
\hline
\end{tabular}
Float Formatting
If in the Table values are of float type and we want to limit them into certain decimal places we use floatfmt = “0.4f” parameter to function tabulate.
from tabulate import tabulate Table = [["No.", "name", "%marks"], [1, "Alice", 96.633333], [2, "bob", 33.333333], [3, "Jon", 60.6767676]] print(tabulate(Table, headers="firstrow",missingval="-", tablefmt="rst", floatfmt="0.2f"))
===== ====== ========
No. name %marks
===== ====== ========
1 Alice 96.63
2 bob 33.33
3 Jon 60.68
===== ====== ========
TermTables
Installation
pip install termtables
Documentation
https://pypi.org/project/termtables/
Usage
Here is a very basic code to display code with termtables
import termtables data = [ [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] termtables.print(data)
Output
┌───┬────────┬───┬────┐
│ 1 │ Bob │ 6 │ 11 │
├───┼────────┼───┼────┤
│ 2 │ Freddy │ 4 │ 10 │
├───┼────────┼───┼────┤
│ 3 │ John │ 7 │ 13 │
└───┴────────┴───┴────┘
Add a header
Pack your header in a list and use the header parameter to display the header
import termtables header = ["No.", "Name", "Grade", "Age"] data = [ [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] termtables.print(data, header=header)
┌─────┬────────┬───────┬─────┐
│ No. │ Name │ Grade │ Age │
╞═════╪════════╪═══════╪═════╡
│ 1 │ Bob │ 6 │ 11 │
├─────┼────────┼───────┼─────┤
│ 2 │ Freddy │ 4 │ 10 │
├─────┼────────┼───────┼─────┤
│ 3 │ John │ 7 │ 13 │
└─────┴────────┴───────┴─────┘
Get the table in string format
You can also get the formatted table in string format if you do not want to display it immediately.
import termtables header = ["No.", "Name", "Grade", "Age"] data = [ [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] table = termtables.to_string(data, header=header) print(table)
┌─────┬────────┬───────┬─────┐
│ No. │ Name │ Grade │ Age │
╞═════╪════════╪═══════╪═════╡
│ 1 │ Bob │ 6 │ 11 │
├─────┼────────┼───────┼─────┤
│ 2 │ Freddy │ 4 │ 10 │
├─────┼────────┼───────┼─────┤
│ 3 │ John │ 7 │ 13 │
└─────┴────────┴───────┴─────┘
Change styles
To change the style, use the style parameter and one of the options from
import termtables header = ["No.", "Name", "Grade", "Age"] data = [ [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] termtables.print( data, header=header, style=termtables.styles.double_thin )
╔═════╦════════╦═══════╦═════╗
║ No. ║ Name ║ Grade ║ Age ║
╟─────╫────────╫───────╫─────╢
║ 1 ║ Bob ║ 6 ║ 11 ║
╠═════╬════════╬═══════╬═════╣
║ 2 ║ Freddy ║ 4 ║ 10 ║
╠═════╬════════╬═══════╬═════╣
║ 3 ║ John ║ 7 ║ 13 ║
╚═════╩════════╩═══════╩═════╝
Following styles are available in termtables.styles
thin = "─│┌┐└┘├┤┬┴┼"
thin_thick = "─│┌┐└┘├┤┬┴┼┝━┿┥"
thin_double = "─│┌┐└┘├┤┬┴┼╞═╪╡"
rounded = "─│╭╮╰╯├┤┬┴┼"
rounded_thick = "─│╭╮╰╯├┤┬┴┼┝━┿┥"
rounded_double = "─│╭╮╰╯├┤┬┴┼╞═╪╡"
thick = "━┃┏┓┗┛┣┫┳┻╋"
thick_thin = "─│┌┐└┘├┤┬┴┼┠─╂┨"
double = "═║╔╗╚╝╠╣╦╩╬"
double_thin = "═║╔╗╚╝╠╣╦╩╬╟─╫╢"
booktabs = "─ ─── ━━ "
ascii_thin = "-|+++++++++"
ascii_thin_double = "-|++++++++++=++"
ascii_double = "=H+++++++++"
ascii_double_thin = "=H++++++++++-++"
ascii_booktabs = "- --- == "
markdown = " | |-||"
TerminalTables or AsciiTable
Installation
pip install terminaltables
Documentation
https://robpol86.github.io/terminaltables/
Usage
Let’s start with the code to display a table with a header
from terminaltables import AsciiTable data = [ ["No.", "Name", "Grade", "Age"], [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] table = AsciiTable(data) print(table.table)
+-----+--------+-------+-----+
| No. | Name | Grade | Age |
+-----+--------+-------+-----+
| 1 | Bob | 6 | 11 |
| 2 | Freddy | 4 | 10 |
| 3 | John | 7 | 13 |
+-----+--------+-------+-----+
Table without header
By default, it considers the first row as the header. If you don’t have the header, you can build the table like this:
from terminaltables import AsciiTable data = [ [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] table = AsciiTable(data) table.inner_heading_row_border = False print(table.table)
+---+--------+---+----+
| 1 | Bob | 6 | 11 |
| 2 | Freddy | 4 | 10 |
| 3 | John | 7 | 13 |
+---+--------+---+----+
Separator for all the rows
If you want to add a border to all the rows, you can set inner_row_border to True.
from terminaltables import AsciiTable data = [ [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] table = AsciiTable(data) table.inner_row_border = True print(table.table)
+---+--------+---+----+
| 1 | Bob | 6 | 11 |
+---+--------+---+----+
| 2 | Freddy | 4 | 10 |
+---+--------+---+----+
| 3 | John | 7 | 13 |
+---+--------+---+----+
Table Title
You can also add a title to the table by setting its title property.
from terminaltables import AsciiTable data = [ [1, "Bob", 6, 11], [2, "Freddy", 4, 10], [3, "John", 7, 13], ] table = AsciiTable(data) table.inner_heading_row_border = False table.title = "Test Table" print(table.table)
+Test Table--+---+----+
| 1 | Bob | 6 | 11 |
| 2 | Freddy | 4 | 10 |
| 3 | John | 7 | 13 |
+---+--------+---+----+
Great article
👌🏻