【2】文件读写-8-1-打印表格多种样式--tabulate

tabulate是一个帮助你打印标准化表单的库,使用起来非常便捷,支持的格式较多

样例:

******************表格样式1*******************
-----  ------  -------------
Sun    696000     1.9891e+09
Earth    6371  5973.6
Moon     1737    73.5
Mars     3390   641.85
-----  ------  -------------
******************表格样式 2******************
Planet      R (km)    mass (x 10^29 kg)
--------  --------  -------------------
Sun         696000           1.9891e+09
Earth         6371        5973.6
Moon          1737          73.5
Mars          3390         641.85
******************表格样式 3******************
Name      Age
------  -----
Alice      24
Bob        19
******************表格样式 4******************
  Age  Name
-----  ------
   24  Alice
   19  Bob
******************表格样式 5******************
+--------+--------+---------------+
| item   |    qty |            dd |
+========+========+===============+
| Sun    | 696000 |    1.9891e+09 |
+--------+--------+---------------+
| Earth  |   6371 | 5973.6        |
+--------+--------+---------------+
| Moon   |   1737 |   73.5        |
+--------+--------+---------------+
| Mars   |   3390 |  641.85       |
+--------+--------+---------------+
******************表格样式 6******************
| item   |    qty |            dd |
|:-------|-------:|--------------:|
| Sun    | 696000 |    1.9891e+09 |
| Earth  |   6371 | 5973.6        |
| Moon   |   1737 |   73.5        |
| Mars   |   3390 |  641.85       |
******************表格样式 7******************
| item   |    qty |            dd |
|--------+--------+---------------|
| Sun    | 696000 |    1.9891e+09 |
| Earth  |   6371 | 5973.6        |
| Moon   |   1737 |   73.5        |
| Mars   |   3390 |  641.85       |

代码:

# -*- coding: utf-8 -*-
"""
from tabulate import tabulate
table = [
    ["Sun",696000,1989100000],["Earth",6371,5973.6],["Moon",1737,73.5],["Mars",3390,641.85]
        ]

print("表格样式1".center(50,'*'))
print(tabulate(table))

print("表格样式 2".center(50,'*'))
print(tabulate(table, headers=["Planet","R (km)", "mass (x 10^29 kg)"]))

print("表格样式 3".center(50,'*'))
print(tabulate([["Name","Age"],["Alice",24],["Bob",19]],headers="firstrow"))

print("表格样式 4".center(50,'*'))
print(tabulate({"Name": ["Alice", "Bob"],"Age": [24, 19]}, headers="keys"))

headers = ["item", "qty",'dd']
print("表格样式 5".center(50,'*'))
print(tabulate(table, headers, tablefmt="grid"))

print("表格样式 6".center(50,'*'))
print(tabulate(table, headers, tablefmt="pipe"))

print("表格样式 7".center(50,'*'))
print(tabulate(table, headers, tablefmt="orgtbl"))

讨论

  • 表格中支持 \n 换行符
  • 其他更多参数见官网
药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn