在 Python 中,对齐和格式化表格数据输出可以通过多种方式实现。以下是几种常见的方法:
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。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
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
等。
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
。tabulate
或 prettytable
库,它们提供了更多的功能和灵活性。根据你的需求和项目的复杂性,选择合适的方法来格式化表格数据。