PrettyTable is an awesome Python library that allows us to generate simple ASCII tables. Not just ASCII tables, you can even use PrettyTable to generate HTML tables. Let’s understand how you can effortlessly import the PrettyTable module in Python.
Step 1: Installation of PrettyTable
Before importing PrettyTable in Python, you must first install it. You can simply use PyPi to install PrettyTable using pip using your terminal or command prompt. Use the following installation command.
1 |
pip install prettytable |
Note: If you have other versions of Python and pip installed, you may need to use either pip3 or pip2.7 instead of pip.
Step 2: Import the PrettyTable Class
Once PrettyTable is installed, you can import it into your Python script. The method is straightforward. You only need to use the import keyword followed by the name of the module which is ‘prettytable’ in this case.
1 |
from prettytable import PrettyTable |
Step 3: Use PrettyTable
After importing the PrettyTable, you can use its numerous functions to generate tables. Below is a simple table creation example.
1 2 3 4 5 6 7 8 9 10 |
x = PrettyTable() x.field_names = ["City name", "Area", "Population", "Annual Rainfall"] x.add_row(["Adelaide",1295, 1158259, 600.5]) x.add_row(["Brisbane",5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print(x) |
This script when executed properly will give you a tabular output with data formatted neatly. The ‘field_names’ method is used to define the column headers. ‘add_row’ is used to add data rows one by one to the table.
Entire Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
pip install prettytable from prettytable import PrettyTable x = PrettyTable() x.field_names = ["City name", "Area", "Population", "Annual Rainfall"] x.add_row(["Adelaide",1295, 1158259, 600.5]) x.add_row(["Brisbane",5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print(x) |
Output
+-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Sydney | 2058 | 4336374 | 1214.8 | | Melbourne | 1566 | 3806092 | 646.9 | | Perth | 5386 | 1554769 | 869.4 | +-----------+------+------------+-----------------+
Conclusion
Successfully installing and importing PrettyTable in Python is as simple as following these steps. It’s a powerful tool that can help you format your data in both ASCII and HTML tables quickly and effortlessly.