杰瑞科技汇

Python PrettyTable如何快速美化表格输出?

Of course! You're asking about PrettyTable, which is a fantastic and popular Python library for creating simple, ASCII-based tables in the console. It's perfect for formatting data in a clean, readable way.

Python PrettyTable如何快速美化表格输出?-图1
(图片来源网络,侵删)

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

What is PrettyTable?

PrettyTable is a Python library that allows you to display tabular data in a visually appealing, ASCII-art table format. It's like creating tables in a word processor, but entirely in your terminal or script output.


Installation

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

pip install prettytable

Creating Your First Simple Table

Let's start with the basics: creating a table with some data.

Python PrettyTable如何快速美化表格输出?-图2
(图片来源网络,侵删)
from prettytable import PrettyTable
# 1. Create a table object
table = PrettyTable()
# 2. Add columns (headers)
table.field_names = ["Pokemon Name", "Type", "HP"]
# 3. 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/Poison", 45])
# 4. Print the table to the console
print(table)

Output:

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

Key Features and Customization

PrettyTable is highly customizable. Here are the most common things you'll want to change.

a. Adding Rows from a List of Lists

If your data is already in a list format, you can add it all at once.

from prettytable import PrettyTable
table = PrettyTable()
table.field_names = ["City", "Country", "Population"]
cities_data = [
    ["Tokyo", "Japan", "37.4 million"],
    ["Delhi", "India", "30.3 million"],
    ["Shanghai", "China", "27.1 million"],
    ["São Paulo", "Brazil", "22.0 million"]
]
table.add_rows(cities_data)
print(table)

b. Alignment

You can align the text in each column.

Python PrettyTable如何快速美化表格输出?-图3
(图片来源网络,侵删)
  • l for left
  • c for center
  • r for right
from prettytable import PrettyTable
table = PrettyTable()
table.field_names = ["Student Name", "Grade", "Status"]
table.align["Student Name"] = "l"  # Left-align
table.align["Grade"] = "c"         # Center-align
table.align["Status"] = "r"        # Right-align
table.add_row(["Alice", "A", "Pass"])
table.add_row(["Bob", "C", "Pass"])
table.add_row(["Charlie", "F", "Fail"])
print(table)

Output:

+--------------+-------+--------+
| Student Name | Grade | Status |
+--------------+-------+--------+
| Alice        |   A   |   Pass |
| Bob          |   C   |   Pass |
| Charlie      |   F   |   Fail |
+--------------+-------+--------+

c. Sorting the Table

You can sort the table based on any column.

from prettytable import PrettyTable
table = PrettyTable()
table.field_names = ["Product", "Price", "In Stock"]
table.add_row(["Laptop", "$999", 10])
table.add_row(["Mouse", "$25", 50])
table.add_row(["Keyboard", "$75", 30])
table.add_row(["Monitor", "$300", 15])
# Sort by the "Price" column
table.sortby = "Price"
print(table)

Output:

+----------+-------+----------+
| Product  | Price | In Stock |
+----------+-------+----------+
|   Mouse  |  $25  |       50 |
| Keyboard |  $75  |       30 |
|  Monitor | $300  |       15 |
|   Laptop | $999  |       10 |
+----------+-------+----------+

d. Hiding the Header

If you don't want to show the column headers, you can turn them off.

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

Output:

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

e. Setting a Title for the Table

Give your table a title to provide more context.

table = PrettyTable()
table.field_names = ["Country", "Capital"]
table.title = "Top 3 Countries by Population"
table.add_row(["India", "New Delhi"])
table.add_row(["China", "Beijing"])
table.add_row(["USA", "Washington, D.C."])
print(table)

Output:

+-------------------------------------+
|     Top 3 Countries by Population     |
+----------+--------------------------+
| Country  |         Capital          |
+----------+--------------------------+
|  India   |        New Delhi         |
|  China   |          Beijing         |
|   USA    | Washington, D.C.         |
+----------+--------------------------+

f. Customizing the Style (Borders)

You can change the characters used for the table's borders. This is great for fitting into different contexts.

  • DEFAULT: The standard look we've seen.
  • MSWORD_FRIENDLY: No corners.
  • PLAIN_COLUMNS: No borders at all.
  • RANDOM: A random style on each run!
from prettytable import PrettyTable
table = PrettyTable()
table.field_names = ["Name", "Role"]
table.add_row(["Guido van Rossum", "Benevolent Dictator for Life"])
table.add_row(["Linus Torvalds", "Creator of Linux"])
print("MSWORD_FRIENDLY Style:")
table.set_style(PrettyTable.MSWORD_FRIENDLY)
print(table)
print("\nPLAIN_COLUMNS Style:")
table.set_style(PrettyTable.PLAIN_COLUMNS)
print(table)

Output:

MSWORD_FRIENDLY Style:
Name                  Role
-------------------------------------------
Guido van Rossum      Benevolent Dictator for Life
Linus Torvalds        Creator of Linux
PLAIN_COLUMNS Style:
Name                  Role
Guido van Rossum      Benevolent Dictator for Life
Linus Torvalds        Creator of Linux

g. Controlling Decimal Places

For numerical data, you can specify the number of decimal places to display.

from prettytable import PrettyTable
table = PrettyTable()
table.field_names = ["Item", "Price", "Tax"]
# Prices are floats
table.add_row(["Apple", 1.05, 0.08])
table.add_row(["Bread", 3.49, 0.28])
table.add_row(["Milk", 2.99, 0.24])
# Format the 'Price' column to 2 decimal places
table.float_format["Price"] = ".2"
print(table)

Output:

+-------+-------+-----+
| Item  | Price | Tax |
+-------+-------+-----+
| Apple |  1.05 | 0.08|
| Bread |  3.49 | 0.28|
|  Milk |  2.99 | 0.24|
+-------+-------+-----+

Complete Example: Displaying SQL Query Results

A very common use case for PrettyTable is formatting the results of a database query.

import sqlite3
from prettytable import PrettyTable
# 1. Create a simple in-memory database and insert some data
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
cursor.execute('''
    CREATE TABLE employees (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        department TEXT,
        salary REAL
    )
''')
employees_data = [
    (1, 'Alice', 'Engineering', 90000.00),
    (2, 'Bob', 'Marketing', 65000.00),
    (3, 'Charlie', 'Engineering', 110000.00),
    (4, 'Diana', 'HR', 60000.00)
]
cursor.executemany('INSERT INTO employees VALUES (?, ?, ?, ?)', employees_data)
conn.commit()
# 2. Execute a query
cursor.execute("SELECT name, department, salary FROM employees WHERE department = 'Engineering'")
# 3. Get the column names and rows
columns = [description[0] for description in cursor.description]
rows = cursor.fetchall()
# 4. Create and populate the PrettyTable
results_table = PrettyTable()
results_table.field_names = columns
results_table.add_rows(rows)
# 5. Customize and print
results_table.title = "Engineering Department Employees"
results_table.align["name"] = "l"
results_table.align["department"] = "c"
results_table.float_format["salary"] = ".2f"
print(results_table)
conn.close()

Output:

+---------------------------------------------+
|     Engineering Department Employees       |
+----------+-------------+----------+
| name     | department  |  salary  |
+----------+-------------+----------+
| Alice    |  Engineering| 90000.00|
| Charlie  |  Engineering|110000.00|
+----------+-------------+----------+

Alternatives to PrettyTable

While PrettyTable is excellent, it's good to know other options:

  • tabulate: Another very popular library. It's known for its simplicity and support for many different output formats (like Markdown, HTML, etc.). It's often seen as a more modern alternative.
    from tabulate import tabulate
    print(tabulate([['Alice', 24], ['Bob', 42]], headers=['Name', 'Age']))
  • Pandas: If you're already working with data in Python, the Pandas library has a built-in .to_string() method that can create tables, and its .style property can create much richer HTML tables for Jupyter Notebooks.
    import pandas as pd
    df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [24, 42]})
    print(df.to_string())

Summary

Feature How to do it with PrettyTable
Create Table table = PrettyTable()
Add Headers table.field_names = ["Col1", "Col2"]
Add Row table.add_row(["Data1", "Data2"])
Add Multiple Rows table.add_rows([["D1", "D2"], ["D3", "D4"]])
Align Text table.align["ColName"] = "l" (or "c", "r")
Sort Table table.sortby = "ColName"
Add Title table.title = "My Table Title"
Change Style table.set_style(PrettyTable.MSWORD_FRIENDLY)
Format Decimals table.float_format["ColName"] = ".2"
Hide Header table.header = False
分享:
扫描分享到社交APP
上一篇
下一篇