学过perl同学都知道perl有Data::Dumper,在python有相同功能模块pprint。接下来会把学习python文档做些笔记,以便以后查阅。pprint能够打印python的数据结构,看起来更直观。
PrettyPrinter类有三个参数:indent, depth, width
indent:展示数据时,缩进多少(每个递归层)
depth:最多显示层级
width:展示一行宽度,默认80
对每层递归都缩进10
>>> import pprint >>> stuff = ['a'*10, 'b'*10, 'c'*10, 'd'*10, 'e'*10] >>> stuff.insert(0, stuff[:]) >>> pp = pprint.PrettyPrinter(indent=10); >>> pp.pprint(stuff) [ [ 'aaaaaaaaaa', 'bbbbbbbbbb', 'cccccccccc', 'dddddddddd', 'eeeeeeeeee'], 'aaaaaaaaaa', 'bbbbbbbbbb', 'cccccccccc', 'dddddddddd', 'eeeeeeeeee']
一共是6层,如果只显示5层,那python就会用”…”来展示为未显示列表
>>> tup = ('a', ('b', ('c', ('d', ('e', ('f',)))))) >>> pp = pprint.PrettyPrinter(depth=6) >>> pp.pprint(tup) ('a', ('b', ('c', ('d', ('e', ('f',)))))) >>> pp = pprint.PrettyPrinter(depth=5) >>> pp.pprint(tup) ('a', ('b', ('c', ('d', ('e', (...,))))))
一共是92个字符,所以width=93时,就可在一行内放下
>>> stuff = ['a'*5, 'b'*5, 'c'*5, 'd'*5, 'e'*5] >>> stuff.insert(0, stuff[:]) >>> pp = pprint.PrettyPrinter(); >>> pp.pprint(stuff) [['aaaaa', 'bbbbb', 'ccccc', 'ddddd', 'eeeee'], 'aaaaa', 'bbbbb', 'ccccc', 'ddddd', 'eeeee'] >>> pp = pprint.PrettyPrinter(width=93); >>> pp.pprint(stuff); [['aaaaa', 'bbbbb', 'ccccc', 'ddddd', 'eeeee'], 'aaaaa', 'bbbbb', 'ccccc', 'ddddd', 'eeeee']
PrettyPrinter的函数:pformat、pprint、isreadable、isrecursive、saferepr
具体参考(http://docs.python.org/library/pprint.html)
pformat以字符串返回
>>> stuff = ['a'*5, 'b'*5, 'c'*5, 'd'*5, 'e'*5] >>> pp = pprint.PrettyPrinter(); >>> pp.pformat(stuff); "['aaaaa', 'bbbbb', 'ccccc', 'ddddd', 'eeeee']"
Print the formatted representation of object on the configured stream(不知道怎么翻译好)
>>> stuff = ['a'*5, 'b'*5, 'c'*5, 'd'*5, 'e'*5] >>> stuff.insert(0, stuff) >>> pprint.pprint(stuff) [<Recursion on list with id=29923736>, 'aaaaa', 'bbbbb', 'ccccc', 'ddddd', 'eeeee']
isreadable来确认对象是否可读,如果是递归对象(多层),就会返回false
>>> stuff = ['a'*5, 'b'*5, 'c'*5, 'd'*5, 'e'*5] >>> pp = pprint.PrettyPrinter(); >>> pp.isreadable(stuff) True >>> stuff.insert(0, stuff) >>> pp.isreadable(stuff) False
isrecursive判断是否是递归对象
>>> stuff = ['a'*5, 'b'*5, 'c'*5, 'd'*5, 'e'*5] >>> pp = pprint.PrettyPrinter(); >>> pp.isrecursive(stuff) False >>> stuff.insert(0, stuff) >>> pp.isrecursive(stuff) True
对递归对象进行保护,递归对象就会显示
>>> pprint.saferepr(stuff) "[<Recursion on list with id=29924312>, 'aaaaa', 'bbbbb', 'ccccc', 'ddddd', 'eeeee']"