
289 views
Prettytable in Python
PrettyTable
is a Python library that allows you to create and display tabular data in a visually appealing and formatted way. It is a convenient tool for generating text-based tables for use in command-line applications, reports, or other textual outputs. To use PrettyTable
, you’ll need to install it first:
pip install prettytable
Here’s a basic example of how to create and display a table using PrettyTable
:
from prettytable import PrettyTable
# Create a PrettyTable object
table = PrettyTable()
# Define table columns
table.field_names = ["Name", "Age", "City"]
# Add rows to the table
table.add_row(["Alice", 30, "New York"])
table.add_row(["Bob", 25, "Los Angeles"])
table.add_row(["Charlie", 35, "Chicago"])
# Print the table
print(table)
In this example:
- We import the
PrettyTable
class from theprettytable
module. - We create a
PrettyTable
object namedtable
. - We define the columns of the table using the
field_names
attribute. - We add rows of data to the table using the
add_row()
method. Each call toadd_row()
adds a new row to the table. - Finally, we print the table, which will display the data in a well-formatted tabular format.
The output will look like this:
+---------+-----+-------------+
| Name | Age | City |
+---------+-----+-------------+
| Alice | 30 | New York |
| Bob | 25 | Los Angeles |
| Charlie | 35 | Chicago |
+---------+-----+-------------+
PrettyTable
provides various options for customizing the table’s appearance, including column alignment, sorting, and more. You can refer to the documentation for more advanced usage: https://ptable.readthedocs.io/en/latest/