简介

Python通过PrettyTable模块可以将输出内容如表格方式整齐地输出。

安装

pip install prettytable
  • 1

示例

from prettytable import PrettyTable
table = PrettyTable(["animal", "ferocity"])
table.add_row(["wolverine", 100])
table.add_row(["grizzly", 87])
table.add_row(["Rabbit of Caerbannog", 110])
table.add_row(["cat", -1])
table.add_row(["platypus", 23])
table.add_row(["dolphin", 63])
table.add_row(["albatross", 44])
table.sort_key("ferocity")
table.reversesort = True
print(table) '''效果图
+----------------------+----------+
| animal | ferocity |
+----------------------+----------+
| Rabbit of Caerbannog | 110 |
| wolverine | 100 |
| grizzly | 87 |
| dolphin | 63 |
| albatross | 44 |
| platypus | 23 |
| cat | -1 |
+----------------------+----------+
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

使用

创建表

直接创建

pt = PrettyTable()
  • 1

从已有文件创建

CSV
from prettytable import from_csv
fp = open("mytable.csv", "r")
pt = from_csv(fp)
fp.close()
  • 1
  • 2
  • 3
  • 4
HTML
from prettytable import from_html
pts = from_html(html_string)
  • 1
  • 2
SQL
from prettytable import from_db_cursor
db_cur.execute("SELECT * FROM mytable")
pt = from_db_cursor(db_cur)
  • 1
  • 2
  • 3

添加元素

按行添加

pt.add_row()
  • 1

按列添加

pt.add_column()
  • 1

输出格式

ASCII码表

直接输出
print(pt)
  • 1
无表格框输出
print(pt.get_string())
  • 1

HTML表

print(pt.get_html_string())
  • 1

选择子表

print(pt.get_string(fields = ["City name", "Population"]))
  • 1
#输出前4列
print(pt.get_string(start = 0, end = 3))
  • 1
  • 2
new_table = old_table[0:3]
print(new_table)
  • 1
  • 2

表排序

print x.get_string(sortby="Annual Rainfall", reversesort=True)
  • 1

控制表样式

自带样式

#参数还可以选择“DEFAULT”、“PLAIN_COLUMNS”
from prettytable import MSWORD_FRIENDLY
x.set_style(MSWORD_FRIENDLY)
print(x)
  • 1
  • 2
  • 3
  • 4

手动控制样式

可调整选项

摘自prettytable文档

  • border - 布尔类型参数(必须是True或False)。控制表格边框是否显示。
  • header - 布尔类型参数(必须是True或False)。控制表格第一行是否作为表头显示。
  • header-style - 控制表头信息的大小写。允许的参数值:“cap”(每个单词首字母大写),“title”(除了介词助词首字母大写),“lower”(全部小写)或者None(不改变原内容格式)。默认参数为None。
  • hrules - 设置表格内部水平边线。允许的参数值:FRAME,ALL,NONE。注意这些是在prettytable模块内部定义的变量,在使用之前导入或用类似prettytable.FRAME的方法调用。
  • vrules - 设置表格内部竖直边线。允许的参数值:FRAME,ALL,NONE。
  • align - 水平对齐方式(None,“l”(左对齐),“c”(居中),“r”右对齐)
  • valign - 垂直对齐方式(None,“t”(顶部对齐),“m”(居中),“b”底部对齐)
  • int_format - 控制整型数据的格式。
  • float_format - 控制浮点型数据的格式。
  • padding_width - 列数据左右的空格数量。(当左右padding未设置时生效)
  • left_padding_width - 列数据左侧的空格数量。
  • right_padding_width - 列数据右侧的空格数量。
  • vertical_char - 绘制竖直边线的字符,默认为“|”
  • horizontal_char - 绘制水平边线的字符,默认为“-”
  • junction_char - 绘制水平竖直交汇点的字符,默认为“+”

  • border - A boolean option (must be True or False). Controls whether or not a border is drawn around the table.
  • header - A boolean option (must be True or False). Controls whether or not the first row of the table is a header showing the names of all the fields.
  • header_style - Controls capitalisation of field names in the header. Allowed values: “cap” (capitalise first letter of each word), “title” (title case), “upper” (all upper-case), “lower” (all lower-case) or None (don’t change from original field name setting). Default is None.
  • hrules - Controls printing of horizontal rules after rows. Allowed values: FRAME, ALL, NONE - note that these are variables defined inside the prettytable module so make sure you import them or use prettytable.FRAME etc.
  • vrules - Controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
  • align - Horizontal alignment (None, “l” (left), “c” (centre), “r” (right))
  • valign - Vertical alignment (None, “t” (top), “m” (middle) or “b” (bottom))
  • int_format - Controls formatting of integer data. This should be a string which can be placed between “%” and “d” in something like print “%d” % 42.
  • float_format - Controls formatting of floating point data. This should be a string which can be placed between “%” and “f” in something like print “%f” % 4.2.
  • padding_width - Number of spaces on either side of column data (only used if left and right paddings are None).
  • left_padding_width - Number of spaces on left hand side of column data.
  • right_padding_width - Number of spaces on right hand side of column data.
  • vertical_char - Single character string used to draw vertical lines. Default is |.
  • horizontal_char - Single character string used to draw horizontal lines. Default is -.
  • junction_char - Single character string used to draw line junctions. Default is +.
用法
x = PrettyTable()
x.border = False
x.header = False
x.padding_width = 5
  • 1
  • 2
  • 3
  • 4
x = PrettyTable(border=False, header=False, padding_width=5)
  • 1

以上两种设置方式等效

调整对齐方式的几种方法
print(x.get_string(align="l"))
  • 1
x.align["City name"] = "l"
x.align["Population"] = "c"
x.align["Area"] = "r"
  • 1
  • 2
  • 3
x.align = "l'
  • 1

参考资料

python prettytable模块的更多相关文章

  1. python prettytable 模块

    #coding:utf-8 # qianxiao996精心制作 from prettytable import PrettyTable x = PrettyTable(["名称", ...

  2. Python模块——PrettyTable 模块

    简介 PrettyTable 是python中的一个第三方库,可用来生成美观的ASCII格式的表格,十分实用. 安装 pip install prettytable 示例 从已有文件创建 CSV fr ...

  3. Python常用模块——目录

    Python常用模块学习 Python模块和包 Python常用模块time & datetime &random 模块 Python常用模块os & sys & sh ...

  4. Python3之PrettyTable模块

    一. 简介 Python通过prettytable模块将输出内容如表格方式整齐输出,python本身并不内置,需要独立安装该第三方库. 二. 安装 方式一:pip安装 >>> pip ...

  5. prettytable模块(格式化打印内容)

    1.查看系统是否已经安装prettytable模块 2.下载prettytable模块 登陆:https://pypi.python.org/pypi/PrettyTable 3.安装PrettyTa ...

  6. python email模块

    python email模块 官方文档 email模块 电子邮件包是一个用于管理电子邮件消息的库.它的特殊设计不用于向SMTP (RFC 2821).NNTP或其他服务器发送任何电子邮件消息;这些是模 ...

  7. Python标准模块--threading

    1 模块简介 threading模块在Python1.5.2中首次引入,是低级thread模块的一个增强版.threading模块让线程使用起来更加容易,允许程序同一时间运行多个操作. 不过请注意,P ...

  8. Python的模块引用和查找路径

    模块间相互独立相互引用是任何一种编程语言的基础能力.对于“模块”这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译型的语言,比如C#中 ...

  9. Python Logging模块的简单使用

    前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...

随机推荐

  1. 数据摘要 MD5

    数据一样,摘要一样  (摘要即MD5) 摘要一样,数据一样 摘要是用于检验数据的完整性的技术(比如验证下载的东西是否完整,迅雷就是这样), 查看文件的MD5: Linux         :  md5 ...

  2. JVM GC-----3、垃圾标记算法(二)

    在上一篇文章中,介绍了在GC机制中,GC是以什么标准判定对象可以被标记的,以及最有效最常用的可达性分析法.今天介绍另外一种非常常用的标记算法,它的应用面也相当广泛.这就是:引用计数法 Referenc ...

  3. UVa 11059 - Maximum Product 最大乘积【暴力】

    题目链接:https://vjudge.net/contest/210334#problem/B 题目大意:Given a sequence of integers S = {S1, S2, . . ...

  4. SSL/TLS中间人攻击

    准备:kali.xp kali ip:192.168.14.157 目标ip:192.168.14.158 目标网关:192.168.14.2 使用工具:ettercap.sslstrip.arpsp ...

  5. Codeforces.392E.Deleting Substrings(区间DP)

    题目链接 \(Description\) \(Solution\) 合法的子序列只有三种情况:递增,递减,前半部分递增然后一直递减(下去了就不会再上去了)(当然还要都满足\(|a_{i+1}-a_i| ...

  6. BZOJ.4892.[TJOI2017]DNA(后缀自动机/后缀数组)

    题目链接 \(Description\) 给出两个串\(S,T\),求\(T\)在\(S\)中出现了多少次.出现是指.可以有\(3\)次(\(3\)个字符)不匹配(修改使其匹配). \(Solutio ...

  7. 洛谷.2325.[SCOI2005]王室联邦(贪心)

    题目链接 比较水的题 然而.. 首先可以考虑DFS 每B个分一个块,但是这样链底不会和上边相连 于是考虑从底下开始分,即在DFS完一个点时才将其加入栈中:当子树size==B时出栈 最后在根节点可能会 ...

  8. Python图形编程探索系列-07-程序登录界面设计

    设计任务 初步设计程序登录界面,详细分析设计步骤. 程序详细分析 基本框架设计 import tkinter as tk import tkinter.messagebox root = tk.Tk( ...

  9. Python3内置函数——reversed() = 翻转我的世界

    认识reversed单词 reversed 英[rɪ'vɜ:st] 美[rɪ'vɜst] adj. 颠倒的:相反的:(判决等)撤销的 v. 颠倒(reverse的过去式和过去分词):翻转 help(r ...

  10. 潭州课堂25班:Ph201805201 第十一课 继承,多继承和魔术方法,属性和方法 (课堂笔记)

    继承: class p : cls_name = 'p' def __init__(self): print('正在实例化') def __del__(self): print('正在销毁') cla ...