36岁学习python第24天:prettytable

prettytable是pyhton内置库,用于创建和展示表格数据。通过pip install prettytable即可安装

from prettytable import PrettyTable
table = PrettyTable()
table.title = "Resume"
# 定义表头
table.field_names = ["name", "age", "gender", "address"]
# 增加一行数据,列表里的元素按照顺序对应表头
table.add_row(["Adelaide", 20, '男', '北京'])
table.add_row(["Brisbane", 30, '男', '北京'])
table.add_row(["Sydney", 35, '男', '上海'])
table.add_row(["Melbourne", 45, '男', '天津'])
table.add_row(["Perth", 50, '女', '河北'])
print(table)
print("增加一列")
# 增加一列,第一个参数是字段,第二个是每行数据新增字段的值
table.add_column("id", ['1', '2', '3', '4', '5'])
print(table)
print("获取指定行")
# 获取指定的行
rows = table.get_string(start=0, end=2)
print(rows)
print("删除指定行")
# 删除第2行,索引从0开始
table.del_row(1)
print(table)
print("删除指定列")
# 根据列名删除指定列
table.del_column("id")
print(table)
html = table.get_html_string()
print(html)
'''
+------------------------------------+
|               Resume               |
+-----------+-----+--------+---------+
|    name   | age | gender | address |
+-----------+-----+--------+---------+
|  Adelaide |  20 |   男   |   北京  |
|  Brisbane |  30 |   男   |   北京  |
|   Sydney  |  35 |   男   |   上海  |
| Melbourne |  45 |   男   |   天津  |
|   Perth   |  50 |   女   |   河北  |
+-----------+-----+--------+---------+
增加一列
+-----------------------------------------+
|                  Resume                 |
+-----------+-----+--------+---------+----+
|    name   | age | gender | address | id |
+-----------+-----+--------+---------+----+
|  Adelaide |  20 |   男   |   北京  | 1  |
|  Brisbane |  30 |   男   |   北京  | 2  |
|   Sydney  |  35 |   男   |   上海  | 3  |
| Melbourne |  45 |   男   |   天津  | 4  |
|   Perth   |  50 |   女   |   河北  | 5  |
+-----------+-----+--------+---------+----+
获取指定行
+----------------------------------------+
|                 Resume                 |
+----------+-----+--------+---------+----+
|   name   | age | gender | address | id |
+----------+-----+--------+---------+----+
| Adelaide |  20 |   男   |   北京  | 1  |
| Brisbane |  30 |   男   |   北京  | 2  |
+----------+-----+--------+---------+----+
删除指定行
+-----------------------------------------+
|                  Resume                 |
+-----------+-----+--------+---------+----+
|    name   | age | gender | address | id |
+-----------+-----+--------+---------+----+
|  Adelaide |  20 |   男   |   北京  | 1  |
|   Sydney  |  35 |   男   |   上海  | 3  |
| Melbourne |  45 |   男   |   天津  | 4  |
|   Perth   |  50 |   女   |   河北  | 5  |
+-----------+-----+--------+---------+----+
删除指定列
+------------------------------------+
|               Resume               |
+-----------+-----+--------+---------+
|    name   | age | gender | address |
+-----------+-----+--------+---------+
|  Adelaide |  20 |   男   |   北京  |
|   Sydney  |  35 |   男   |   上海  |
| Melbourne |  45 |   男   |   天津  |
|   Perth   |  50 |   女   |   河北  |
+-----------+-----+--------+---------+
'''
原文链接:,转发请注明来源!