插件窝 干货文章 Python 中如何对齐和格式化表格数据输出

Python 中如何对齐和格式化表格数据输出

Occupation width 表格 tabulate 259    来源:    2025-03-14

在 Python 中,对齐和格式化表格数据输出可以通过多种方式实现。以下是几种常见的方法:

1. 使用字符串的 format 方法

Python 的字符串 format 方法允许你指定字段的宽度和对齐方式。

data = [
    ("Alice", 24, "Engineer"),
    ("Bob", 30, "Doctor"),
    ("Charlie", 22, "Artist")
]

# 定义列宽
col_width = 10

# 打印表头
print("{:<{}} {:<{}} {:<{}}".format("Name", col_width, "Age", col_width, "Occupation", col_width))

# 打印数据
for name, age, occupation in data:
    print("{:<{}} {:<{}} {:<{}}".format(name, col_width, age, col_width, occupation, col_width))

输出:

Name       Age        Occupation
Alice      24         Engineer  
Bob        30         Doctor    
Charlie    22         Artist    
  • :< 表示左对齐,>: 表示右对齐,^: 表示居中对齐。
  • col_width 是列的宽度。

2. 使用 f-string(Python 3.6+)

f-string 是 Python 3.6 引入的一种更简洁的字符串格式化方式。

data = [
    ("Alice", 24, "Engineer"),
    ("Bob", 30, "Doctor"),
    ("Charlie", 22, "Artist")
]

# 定义列宽
col_width = 10

# 打印表头
print(f"{'Name':<{col_width}} {'Age':<{col_width}} {'Occupation':<{col_width}}")

# 打印数据
for name, age, occupation in data:
    print(f"{name:<{col_width}} {age:<{col_width}} {occupation:<{col_width}}")

输出与上面相同。

3. 使用 tabulate

tabulate 是一个第三方库,可以轻松地将数据格式化为表格。

首先安装 tabulate

pip install tabulate

然后使用它来格式化表格:

from tabulate import tabulate

data = [
    ["Alice", 24, "Engineer"],
    ["Bob", 30, "Doctor"],
    ["Charlie", 22, "Artist"]
]

headers = ["Name", "Age", "Occupation"]

# 使用 tabulate 格式化表格
print(tabulate(data, headers=headers, tablefmt="pretty"))

输出:

+---------+-----+------------+
| Name    | Age | Occupation |
+---------+-----+------------+
| Alice   | 24  | Engineer   |
| Bob     | 30  | Doctor     |
| Charlie | 22  | Artist     |
+---------+-----+------------+

tabulate 支持多种表格格式,如 plain, simple, grid, fancy_grid, pipe, orgtbl, jira, presto, psql, rst, mediawiki, moinmoin, youtrack, html, latex, latex_raw, latex_booktabs, textile 等。

4. 使用 prettytable

prettytable 是另一个用于生成美观表格的第三方库。

首先安装 prettytable

pip install prettytable

然后使用它来格式化表格:

from prettytable import PrettyTable

table = PrettyTable()
table.field_names = ["Name", "Age", "Occupation"]

data = [
    ("Alice", 24, "Engineer"),
    ("Bob", 30, "Doctor"),
    ("Charlie", 22, "Artist")
]

for row in data:
    table.add_row(row)

print(table)

输出:

+---------+-----+------------+
|   Name  | Age | Occupation |
+---------+-----+------------+
|  Alice  |  24 |  Engineer  |
|   Bob   |  30 |   Doctor   |
| Charlie |  22 |   Artist   |
+---------+-----+------------+

总结

  • 对于简单的表格,可以使用字符串的 format 方法或 f-string
  • 对于更复杂的表格,推荐使用 tabulateprettytable 库,它们提供了更多的功能和更好的可读性。

根据你的需求选择合适的工具来格式化表格数据。