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

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

格式化 Occupation 表格 prettytable 193    来源:    2025-03-13

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

1. 使用字符串的 format 方法

str.format() 方法可以用来格式化字符串,并且可以通过指定宽度和对齐方式来对齐表格数据。

# 示例数据
data = [
    ("Alice", 24, "Engineer"),
    ("Bob", 30, "Doctor"),
    ("Charlie", 22, "Artist")
]

# 表头
headers = ("Name", "Age", "Occupation")

# 格式化输出
print("{:<10} {:<5} {:<10}".format(*headers))
print("-" * 27)

for name, age, occupation in data:
    print("{:<10} {:<5} {:<10}".format(name, age, occupation))

输出:

Name       Age   Occupation
---------------------------
Alice      24    Engineer  
Bob        30    Doctor    
Charlie    22    Artist    
  • {:<10} 表示左对齐,宽度为 10。
  • {:^10} 表示居中对齐,宽度为 10。
  • {:>10} 表示右对齐,宽度为 10。

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

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

# 示例数据
data = [
    ("Alice", 24, "Engineer"),
    ("Bob", 30, "Doctor"),
    ("Charlie", 22, "Artist")
]

# 表头
headers = ("Name", "Age", "Occupation")

# 格式化输出
print(f"{headers[0]:<10} {headers[1]:<5} {headers[2]:<10}")
print("-" * 27)

for name, age, occupation in data:
    print(f"{name:<10} {age:<5} {occupation:<10}")

输出:

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

3. 使用 tabulate

tabulate 是一个第三方库,可以方便地生成格式化的表格。

首先,安装 tabulate 库:

pip install tabulate

然后使用 tabulate 来格式化表格数据:

from tabulate import tabulate

# 示例数据
data = [
    ["Alice", 24, "Engineer"],
    ["Bob", 30, "Doctor"],
    ["Charlie", 22, "Artist"]
]

# 表头
headers = ["Name", "Age", "Occupation"]

# 格式化输出
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

然后使用 prettytable 来格式化表格数据:

from prettytable import PrettyTable

# 创建表格对象
table = PrettyTable()

# 添加表头
table.field_names = ["Name", "Age", "Occupation"]

# 添加数据
table.add_row(["Alice", 24, "Engineer"])
table.add_row(["Bob", 30, "Doctor"])
table.add_row(["Charlie", 22, "Artist"])

# 输出表格
print(table)

输出:

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

总结

  • 对于简单的表格格式化,可以使用 str.format()f-string
  • 对于更复杂的表格格式化,推荐使用 tabulateprettytable 库,它们提供了更多的功能和灵活性。

根据你的需求和项目的复杂性,选择合适的方法来格式化表格数据。