Python标准库参考笔记-pprint
9.18 pprint
地址:http://docs.python.org/library/pprint.html
以漂亮的格式打印。打印输出可以作为解释器的合法输入。
# -*- coding: cp936 -*-
import copy
import pprint
a = [1,2,3,4]
b = [a,a,a,a,a,a,a,a,a]
print '-------------print----------------'
print b
print '-------------pprint----------------'
pprint.pprint(b)
运行结果:
>>>
-------------print----------------
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
-------------pprint----------------
[[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]]
可以控制输出的深度、宽度和缩进,例如:
# -*- coding: cp936 -*-
import copy
import pprint
a = [1,2,3,4]
b = [a,a,a,a,a,a,a,a,a]
pp = pprint.PrettyPrinter(indent=4)
print '-------------print----------------'
print b
print '-------------pprint----------------'
pprint.pprint(b)
print '-------------pp.pprint----------------'
pp.pprint(b)
结果:
>>>
-------------print----------------
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
-------------pprint----------------
[[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]]
-------------pp.pprint----------------
[ [1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]]
PyMOTW: