python---PrettyTable

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python---PrettyTable相关的知识,希望对你有一定的参考价值。

简介

Python通过prettytable模块将输出内容如表格方式整齐输出,python本身并不内置,需要独立安装该第三方库。

安装

1 pip install PrettyTable
1 #源码安装
2 wget https://pypi.python.org/packages/source/P/PrettyTable/prettytable-0.7.2.tar.gz
3 tar -zxvf prettytable-0.7.2.tar.gz
4 python setup.py build
5 python setup.py install

使用

 1 >>> from prettytable import PrettyTable
 2 >>> x = PrettyTable(["name", "age", "sex", "money"])
 3 >>> x.align["name"] = "l"  # 以name字段左对齐
 4 >>> x.padding_width = 1   # 填充宽度
 5 >>> x.add_row(["xue",20, "man", 1000])
 6 >>> x.add_row(["chen",21, "man", 2000])
 7 >>> x.add_row(["yang",22, "man", 3000])
 8 >>> print(x)
 9 +-------+-----+-----+-------+
10 |  name | age | sex | money |
11 +-------+-----+-----+-------+
12 |  xue  |  20 | man |  1000 |
13 |  chen |  21 | man |  2000 |
14 | yang  |  22 | man |  3000 |
15 +-------+-----+-----+-------+
 1 from prettytable import PrettyTable  
 2 
 3 x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])  
 4 
 5 x.align["City name"] = "l"# Left align city names
 6 
 7 x.padding_width = 1# One space between column edges and contents (default)
 8 
 9 x.add_row(["Adelaide",1295, 1158259, 600.5])  
10 
11 x.add_row(["Brisbane",5905, 1857594, 1146.4])  
12 
13 x.add_row(["Darwin", 112, 120900, 1714.7])  
14 
15 x.add_row(["Hobart", 1357, 205556, 619.5])  
16 
17 x.add_row(["Sydney", 2058, 4336374, 1214.8])  
18 
19 x.add_row(["Melbourne", 1566, 3806092, 646.9])  
20 
21 x.add_row(["Perth", 5386, 1554769, 869.4])  
22 
23 
24 print x 

 

以上是关于python---PrettyTable的主要内容,如果未能解决你的问题,请参考以下文章

python -PrettyTable

python 用 prettytable 输出漂亮的表格

Python Prettytable 分隔每个表

你值得拥有!prettytable:一款专业输出文本化表格的 Python 库!

具有多个标题/标题的 Python PrettyTable

Python prettytable 没有模块,但模块在那里[关闭]