>>> table = [['First Name', 'Last Name', 'Age'], ['John', 'Smith', 39], ['Mary', 'Jane', 25], ['Jennifer', 'Doe', 28]] >>> print(tabulate(table)) ---------- --------- --- First Name Last Name Age John Smith 39 Mary Jane 25 Jennifer Doe 28
设定表头
1 2 3 4 5 6
>>> print(tabulate(table, headers='firstrow')) First Name Last Name Age ------------ ----------- ----- John Smith 39 Mary Jane 25 Jennifer Doe 28
>>> print(tabulate(table, headers='firstrow', tablefmt='fancy_grid')) ╒══════════════╤═════════════╤═══════╕ │ First Name │ Last Name │ Age │ ╞══════════════╪═════════════╪═══════╡ │ John │ Smith │ 39 │ ├──────────────┼─────────────┼───────┤ │ Mary │ Jane │ 25 │ ├──────────────┼─────────────┼───────┤ │ Jennifer │ Doe │ 28 │ ╘══════════════╧═════════════╧═══════╛ >>> print(tabulate(table, headers='firstrow', tablefmt='grid')) +--------------+-------------+-------+ | First Name | Last Name | Age | +==============+=============+=======+ | John | Smith | 39 | +--------------+-------------+-------+ | Mary | Jane | 25 | +--------------+-------------+-------+ | Jennifer | Doe | 28 | +--------------+-------------+-------+
使用 dict 生成表格
1 2 3 4 5 6 7 8 9 10 11
>>> info = {'First Name': ['John', 'Mary', 'Jennifer'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]} >>> print(tabulate(info, headers='keys', tablefmt='grid')) +--------------+-------------+-------+ | First Name | Last Name | Age | +==============+=============+=======+ | John | Smith | 39 | +--------------+-------------+-------+ | Mary | Jane | 25 | +--------------+-------------+-------+ | Jennifer | Doe | 28 | +--------------+-------------+-------+
显示索引
1 2 3 4 5 6 7 8 9 10
>>> print(tabulate(info, headers='keys', tablefmt='grid', showindex=True)) +----+--------------+-------------+-------+ | | First Name | Last Name | Age | +====+==============+=============+=======+ | 0 | John | Smith | 39 | +----+--------------+-------------+-------+ | 1 | Mary | Jane | 25 | +----+--------------+-------------+-------+ | 2 | Jennifer | Doe | 28 | +----+--------------+-------------+-------+
prettytable
安装、导入
1 2
pip install prettytable from prettytable import PrettyTable