PrettyTable
It is simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables. It was inspired by the ASCII tables used in the PostgreSQL shell psql. PrettyTable allows for selection of which columns are to be printed, independent alignment of columns (left or right justified or centred) and printing of “sub-tables” by specifying a row range.
Official Document : Link
There could be many uses cases while using it, here in this blog post we will cover how we can extract our desired cell values from preetyTable.
So we will start by
- Importing module
- Creating object
- Add Feilds
- Add Data
from prettytable import PrettyTable # importing module
tabular_table = PrettyTable() # creating object
tabular_fields = ["Name", "Age", "Gender"] # Define Field List
tabular_table.field_names = tabular_fields # Add Fields to table
tabular_table.add_row(["Tokyo", "33", "M"]) # Add Data
tabular_table.add_row(["Narobi", "74", "M"])
tabular_table.add_row(["Denver", "21", "F"])
print(tabular_table)
Output.
+--------+-----+--------+
| Name | Age | Gender |
+--------+-----+--------+
| Tokyo | 33 | M |
| Narobi | 74 | M |
| Denver | 21 | F |
+--------+-----+--------+
Use Case 1.
- Extract cell values for a specific field only from prettyTable
Below For loop will help to do so.
for row in tabular_table:
print (row.get_string(fields=["Name"]))
Output.
+-------+
| Name |
+-------+
| Tokyo |
+-------+
+--------+
| Name |
+--------+
| Narobi |
+--------+
+--------+
| Name |
+--------+
| Denver |
+--------+
Use Case 2.
- Extract cell values without header or border from prettyTable
for row in tabular_table:
row.border = False
row.header = False
print (row.get_string(fields=["Name"]).strip())
Output.
Tokyo
Narobi
Denver