全部博文(2065)
分类: Python/Ruby
2010-04-21 20:52:55
以漂亮的格式打印。打印输出可以 作为解释器的合法输入。
# -*- 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]]
以后可以用这个模块来代替print了!