美化输出
pprint
格式化输出数据,便于阅读调试
from pprint import PrettyPrinter, pprint
# pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False)
stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
stuff.insert(0, stuff[:])
PrettyPrinter(indent=4).pprint(stuff)
# PrettyPrinter返回一个配置的PrettyPrinter实例,上面例子里设定了4个空格的缩进,而默认为1
# 之后输出
pprint(stuff, indent=4) # 与上面的输出一样
[ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
'spam',
'eggs',
'lumberjack',
'knights',
'ni']
colorama
from colorama import Fore, Back, Style
# Fore 字体颜色
# Back 字体背景颜色
# Style 字体粗细
Basic Usage
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print('these text has the same font color') # 这里打印出的字体仍是绿色
print(Back.GREEN + 'and with a green background')
print(Style.BRIGHT + 'and in dim text') # 粗体
print(Style.RESET_ALL) # 样式全部重置
print('back to normal now')
需要注意的是,在添加任意一种样式之后,如果后面的print没有再设置其他样式,则将一直保持最后一次设置的样式
Options
Fore # BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back # BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Style # DIM, NORMAL, BRIGHT, RESET_ALL
# Style.RESET_ALL 可以重置所有样式
prettytable
以表格的形式输出数据
$ pip3 install prettytable
Basic Usage
from prettytable import PrettyTable
table_headers = ['column1', 'column2', 'column3']
table = PrettyTable(table_headers) # 创建一个带有表格题头的table
for i in range(3): # 创建3行
table.add_row([t for t in range(3)]) # 每行都添加[0, 1, 2]
print(table)
output
+---------+---------+---------+
| column1 | column2 | column3 |
+---------+---------+---------+
| 0 | 1 | 2 |
| 0 | 1 | 2 |
| 0 | 1 | 2 |
+---------+---------+---------+
Enhance
# ...接着上面的table
table.align["column1"] = "l" # 将制定列进行左对齐, 默认为"c"居中对齐
table.valign = "m" # 垂直居中,参数也可以是 "t"顶部对齐/"b"底部对齐
# x.align = "l"/"c"/"r" 可以将所有列都左/居中/右对齐
table.border = False # table是否有border(默认为True)
print(table)
column1 column2 column3
0 1 2
0 1 2
0 1 2