首页 > 代码库 > python---PrettyTable

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.gz3 tar -zxvf prettytable-0.7.2.tar.gz4 python setup.py build5 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