【Python】【tabulate】 資料格式化排版工具
安裝
pip3 install tabulate
範例
from tabulate import tabulate
data = [
["Alice", 25, "Engineer"],
["Bob", 30, "Developer"],
["Charlie", 35, "Manager"],
]
headers = ["Name", "Age", "Job"]
table = tabulate(data, headers=headers, tablefmt="psql")
print(table)
+---------+-----+------------+
| Name | Age | Job |
|---------+-----+------------|
| Alice | 25 | Engineer |
| Bob | 30 | Developer |
| Charlie | 35 | Manager |
+---------+-----+------------+
你可以根據需要選擇不同的表格格式,例如 "plain"
、"simple"
、"grid"
等。tabulate
模組還支援對齊選項、數值格式化等功能,
tabulate
模組的 tablefmt
參數用於指定要使用的表格格式。下面列出了一些常用的 tablefmt
參數值:
-
"plain"
: 這是默認的表格格式,使用簡單的 ASCII 字符。 -
"simple"
: 使用更精簡的 ASCII 字符繪製表格。 -
"grid"
: 使用 ASCII 字符繪製網格狀的表格。 -
"fancy_grid"
: 使用更複雜的 ASCII 字符繪製網格狀的表格。 -
"pipe"
: 使用竖线字符|
繪製表格。 -
"orgtbl"
: 使用+
和-
字符繪製表格。 -
"jira"
: 生成符合 Jira Wiki 格式的表格。 -
"presto"
: 生成符合 Presto 命令行客戶端輸出的表格格式。 -
"pretty"
: 使用 Unicode 字符繪製表格,具有較好的可讀性。
這只是 tablefmt
參數的一些常見值,tabulate
還支援其他一些特殊格式,如 HTML、LaTeX 等。你可以參考 tabulate
模組的官方文件以獲取完整的 tablefmt
參數列表和相應的表格格式示例。