pprint 是 “pretty printer” 的简写,“pretty” 的含义是 “漂亮的、美观的”,因此 pprint 的含义便是:漂亮的打印。
这是个相当简单却有用的模块,主要用于打印复杂的数据结构对象,例如多层嵌套的列表、元组和字典等。
先看看 print() 打印的一个例子:
mylist = ["Beautiful is better than ugly.", "Explicit is better than implicit.", "Simple is better than complex.", "Complex is better than complicated."]
print(mylist)
['Beautiful is better than ugly.', 'Explicit is better than implicit.', 'Simple is better than complex.', 'Complex is better than complicated.']
这是一个简单的例子,全部打印在一行里。如果对象中的元素是多层嵌套的内容(例如复杂的 字典 数据),再打印出那肯定是一团糟的,不好阅读。
使用 pprint 模块的 pprint() 替代 print(),可以解决如下痛点:
设置合适的行宽度,作适当的换行
设置打印的缩进、层级,进行格式化打印
判断对象中是否有无限循环,并优化打印内容
基本使用
pprint(object, stream=None, indent=1, width=80, depth=None, *,compact=False)
默认的行宽度参数为 80,当打印的字符小于 80 时,pprint() 基本上等同于内置函数 print(),当字符超出时,它会作美化,进行格式化输出。
import pprint
mylist = ["Beautiful is better than ugly.", "Explicit is better than implicit.", "Simple is better than complex.", "Complex is better than complicated."]
pprint.pprint(mylist)
超出80字符,打印的元素是换行的
['Beautiful is better than ugly.',
'Explicit is better than implicit.',
'Simple is better than complex.',
'Complex is better than complicated.']
设置缩进
pprint.pprint(mylist, indent=4)
[ 'Beautiful is better than ugly.',
'Explicit is better than implicit.',
'Simple is better than complex.',
'Complex is better than complicated.']
设置打印行宽
mydict = {'students': [{'name':'Tom', 'age': 18},{'name':'Jerry', 'age': 19}]}
pprint.pprint(mydict)
正常打印
{'students': [{'age': 18, 'name': 'Tom'}, {'age': 19, 'name': 'Jerry'}]}
pprint.pprint(mydict, width=20)
行宽为 20
{'students': [{'age': 18,
'name': 'Tom'},
{'age': 19,
'name': 'Jerry'}]}
pprint.pprint(mydict, width=70)
行宽为 70
{'students': [{'age': 18, 'name': 'Tom'},
{'age': 19, 'name': 'Jerry'}]}
设置打印层级
newlist = [1, [2, [3, [4, [5]]]]]
pprint.pprint(newlist, depth=3)
超出的层级会用 ... 表示
[1, [2, [3, [...]]]]
用 pprint 替换 print
import pprint
print = pprint.pprint
mylist = ["Beautiful is better than ugly.", "Explicit is better than implicit.", "Simple is better than complex.", "Complex is better than complicated."]
print(mylist)
['Beautiful is better than ugly.',
'Explicit is better than implicit.',
'Simple is better than complex.',
'Complex is better than complicated.']
更多用法请查看官方文档
总体而言,pprint() 是 print() 的轻量级替代,简单实用,非常方便,而且还是 Python 标准库。