编程语言
首页 > 编程语言> > Python表格输出长数据自动换行[最佳实践]

Python表格输出长数据自动换行[最佳实践]

作者:互联网

解析

用到PrettyTable来打印表格

然后用到textwrap来处理自动换行

注意事项

如果是字典类型(或者其他类型),需要先 str(your_dict) , 然后再填入fill, 不然width不生效

代码演示

#!/bin/python3
# coding: utf-8
import prettytable
from textwrap import fill
from prettytable import ALL as ALL
items_table = prettytable.PrettyTable(hrules=ALL)
items_table.field_names = ["id", "name", "comment"]

items = [
    {
        "id": "1",
        "name": "Alvina Skiles",
        "comment": 'Dolor qui rerum est sed. Sed ipsa repudiandae et. Non explicabo voluptas impedit rerum dignissimos. Minima voluptatibus'
    },
    {
        "id": "2",
        "name" : 'Chasity Lakin',
        "comment": 'Nesciunt ea voluptatem rerum eos rerum ut soluta. Animi totam rerum fugiat consectetur odio et repellendus.'
    },
    {
        "id": "3",
        "name" : 'Miss Brennan Kiehn',
        "comment": 'Nulla placeat saepe voluptatem molestias dolores ex. Reiciendis nostrum adipisci qui enim explicabo.'
    },
]


for item in items:
    # 如果是字典类型,需要先 str(your_dict) , 然后再填入fill, 不然width不生效
    items_table.add_row([item["id"], item["name"], fill(item["comment"], width=50)])

print(items_table)

运行结果

+----+--------------------+---------------------------------------------------+
| id |        name        |                      comment                      |
+----+--------------------+---------------------------------------------------+
| 1  |   Alvina Skiles    | Dolor qui rerum est sed. Sed ipsa repudiandae et. |
|    |                    | Non explicabo voluptas impedit rerum dignissimos. |
|    |                    |                Minima voluptatibus                |
+----+--------------------+---------------------------------------------------+
| 2  |   Chasity Lakin    | Nesciunt ea voluptatem rerum eos rerum ut soluta. |
|    |                    |    Animi totam rerum fugiat consectetur odio et   |
|    |                    |                    repellendus.                   |
+----+--------------------+---------------------------------------------------+
| 3  | Miss Brennan Kiehn |  Nulla placeat saepe voluptatem molestias dolores |
|    |                    |      ex. Reiciendis nostrum adipisci qui enim     |
|    |                    |                     explicabo.                    |
+----+--------------------+---------------------------------------------------+

参考链接

https://www.coder.work/article/6896603
https://www.jianshu.com/p/a33d63935ad8

标签:comment,+----+--------------------+---------------------------------------------
来源: https://blog.csdn.net/neve_give_up_dan/article/details/118812311