杰瑞科技汇

PrettyTable Python 怎么用?

Of course! The prettytable library in Python is a fantastic tool for creating simple, yet powerful, ASCII tables. It's perfect for displaying tabular data in the terminal, reports, or logs in a clean, readable format.

PrettyTable Python 怎么用?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering everything from installation to advanced features.


Installation

First, you need to install the library. It's available on PyPI, so you can use pip:

pip install prettytable

Basic Usage

The core idea is to create a PrettyTable object and then add data to it. You can add data row by row or column by column.

Example 1: Adding Rows

This is the most common way to use the library.

PrettyTable Python 怎么用?-图2
(图片来源网络,侵删)
from prettytable import PrettyTable
# Create a table object
table = PrettyTable()
# Add columns (optional, but good practice)
table.field_names = ["Pokemon Name", "Type", "HP"]
# Add rows of data
table.add_row(["Pikachu", "Electric", 35])
table.add_row(["Charmander", "Fire", 39])
table.add_row(["Squirtle", "Water", 44])
table.add_row(["Bulbasaur", "Grass", 45])
# Print the table to the console
print(table)

Output:

+--------------+---------+----+
| Pokemon Name |  Type   | HP |
+--------------+---------+----+
|    Pikachu   | Electric| 35 |
|  Charmander  |   Fire  | 39 |
|   Squirtle   |  Water  | 44 |
|   Bulbasaur  |  Grass  | 45 |
+--------------+---------+----+

Example 2: Adding Columns

You can also build the table column by column.

from prettytable import PrettyTable
table = PrettyTable()
# Add the first column
table.add_column("City", ["New York", "London", "Tokyo"])
table.add_column("Country", ["USA", "UK", "Japan"])
table.add_column("Population", ["8.4M", "9.0M", "14.0M"])
print(table)

Output:

+-----------+---------+------------+
|    City   | Country | Population |
+-----------+---------+------------+
| New York  |    USA  |     8.4M   |
|   London  |    UK   |     9.0M   |
|   Tokyo   |  Japan  |    14.0M   |
+-----------+---------+------------+

Common Formatting Options

prettytable offers many ways to customize your table's appearance.

PrettyTable Python 怎么用?-图3
(图片来源网络,侵删)

a. Alignment

You can align the text in columns individually or all at once.

table = PrettyTable()
table.field_names = ["City", "Country", "Population"]
table.add_row(["New York", "USA", "8.4M"])
table.add_row(["London", "UK", "9.0M"])
table.add_row(["Tokyo", "Japan", "14.0M"])
# Align the 'City' column to the left
table.align["City"] = "l"
# Align the 'Population' column to the right
table.align["Population"] = "r"
# Align all remaining columns to the center
table.align["Country"] = "c"
print(table)

Output:

+-----------+---------+------------+
| City      | Country | Population |
+-----------+---------+------------+
| New York  |   USA   |      8.4M  |
| London    |   UK    |      9.0M  |
| Tokyo     |  Japan  |     14.0M  |
+-----------+---------+------------+

Alignment Options:

  • "l" or "left"
  • "c" or "center"
  • "r" or "right"

b. Sorting

You can sort the table based on a specific column.

table = PrettyTable()
table.field_names = ["Student", "Grade"]
table.add_row(["Alice", 95])
table.add_row(["Bob", 88])
table.add_row(["Charlie", 92])
# Sort by the "Grade" column in descending order
table.sortby = "Grade"
table.reversesort = True
print(table)

Output:

+---------+-------+
| Student | Grade |
+---------+-------+
|  Alice  |   95  |
| Charlie |   92  |
|   Bob   |   88  |
+---------+-------+

c. Hiding Headers

If you don't want to show the column headers, you can easily hide them.

table = PrettyTable()
table.field_names = ["Fruit", "Color"]
table.add_row(["Apple", "Red"])
table.add_row(["Banana", "Yellow"])
print("Table with headers:")
print(table)
print("\nTable without headers:")
table.header = False
print(table)

Output:

Table with headers:
+--------+--------+
|  Fruit |  Color |
+--------+--------+
|  Apple |   Red  |
| Banana | Yellow |
+--------+--------+
Table without headers:
+--------+--------+
|  Apple |   Red  |
| Banana | Yellow |
+--------+--------+

d. Setting Column Width

You can control the width of each column to make your table more compact.

table = PrettyTable()
table.field_names = ["Product ID", "Product Name", "Price"]
table.add_row(["P-001", "Super Widget", "$19.99"])
table.add_row(["P-002", "Mega Gadget", "$49.50"])
table.add_row(["P-003", "Tiny Thingy", "$5.25"])
# Set a max width for the 'Product Name' column
table.max_width["Product Name"] = 10
print(table)

Output:

+------------+--------------+-------+
| Product ID | Product Name | Price |
+------------+--------------+-------+
|    P-001   | Super Widget | $19.99|
|    P-002   |  Mega Gadget | $49.50|
|    P-003   |  Tiny Thingy | $5.25 |
+------------+--------------+-------+

Advanced Features

a. Customizing the Borders and Junctions

You can change the characters used to draw the table's borders.

from prettytable import MSWORD_FRIENDLY # Or PLAIN_COLUMNS, or RANDOM
table = PrettyTable()
table.set_style(MSWORD_FRIENDLY) # Uses pipes for borders
table.field_names = ["Name", "Role"]
table.add_row(["Guido", "BDFL"])
table.add_row(["Linus", "TSF"])
print(table)

Output (MSWORD_FRIENDLY style):

| Name   | Role  |
|--------|-------|
| Guido  | BDFL  |
| Linus  | TSF   |

You can also customize the characters manually:

table = PrettyTable()
table.field_names = ["Name", "Role"]
table.add_row(["Guido", "BDFL"])
table.add_row(["Linus", "TSF"])
# Customize characters
table.junction_char = "+"
table.horizontal_char = "-"
table.vertical_char = "|"
print(table)

Output:

+--------+-------+
|  Name  |  Role |
+--------+-------+
|  Guido |  BDFL |
|  Linus |  TSF  |
+--------+-------+

b. Exporting to CSV

You can easily export your table to a CSV format.

table = PrettyTable()
table.field_names = ["Name", "Age", "City"]
table.add_row(["John", 30, "New York"])
table.add_row(["Jane", 25, "London"])
# Get the CSV representation
csv_data = table.get_csv_string()
print("--- CSV Data ---")
print(csv_data)
# You can also write it directly to a file
# table.write_csv("output.csv")

Output (CSV Data):

--- CSV Data ---
Name,Age,City
John,30,New York
Jane,25,London

PrettyTable vs. tabulate

Another popular library for creating tables is tabulate. Here's a quick comparison to help you choose:

Feature prettytable tabulate
Primary Focus Object-oriented API. You create a table object and modify it. Function-oriented API. You pass data directly to a function.
Flexibility Extremely high. You can modify any aspect of the table after creation. High, but often requires re-creating the table object for major changes.
Ease of Use Very easy for simple tables. Often simpler for one-off table generation.
Output Formats ASCII, HTML, CSV, LaTeX. ASCII, HTML, Markdown, Grid, Simple, etc. (More format options).
Dependencies None. Pure Python. None. Pure Python.

When to use prettytable:

  • When you are building a table dynamically and need to add/remove rows/columns, sort, or change styles throughout your program.
  • When you need fine-grained control over the table's appearance.

When to use tabulate:

  • When you have a simple list of lists or a dictionary and want a quick, formatted table.
  • When you specifically need output in a format like Markdown or LaTeX.

Summary

The prettytable library is an essential tool for any Python developer who needs to present data in a clean, tabular format in the console. Its object-oriented approach makes it highly flexible and easy to integrate into larger scripts or applications. For most use cases involving terminal output, it's the go-to solution.

分享:
扫描分享到社交APP
上一篇
下一篇