pprint模块提供了打印任意python数据结构的方法,如果这个数据结构不是python的基本类型,则可能无法打印结果。
pprint模块定义了一个类:
pprint.PrettyPrinter(...)
构造一个PrettyPrinter实例,通过stream参数设置输出流,默认为sys.stdout,其它三个可选参数用来控制输出格式,indent:缩进,默认为1;depth:控制输出的层数,如果要打印的的数据结构层数太多,超出的层数将以...输出,默认情况下,对输出层数是没有限制的;width,输出宽度,默认为80个字母。
示例
>>>import pprint
>>> stuff =['spam','eggs','lumberjack','knights','ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[['spam','eggs','lumberjack','knights','ni'],
'spam',
'eggs',
'lumberjack',
'knights',
'ni']
>>> tup =('spam',('eggs',('lumberjack',('knights',('ni',('dead',
...('parrot',('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam',('eggs',('lumberjack',('knights',('ni',('dead',(...)))))))
PrettyPrinter支持一下几种方法:
pprint.pformat(object[, indent[, width[, depth]]])
返回一个格式化的字符串
pprint.pprint(object[, stream[, indent[, width[, depth]]]])
在输出流中打印格式化信息,如果没有提供stream,则默认使用sys.out。
>>>import pprint
>>> stuff =['spam','eggs','lumberjack','knights','ni']
>>> stuff.insert(0, stuff)
>>> pprint.pprint(stuff)
[<Recursion on list with id=...>,
'spam',
'eggs',
'lumberjack',
'knights',
'ni']
pprint.isreadable(object)
判断对象的表示是否'可读',如果是递归对象,则返回False
pprint.isrecursive(object)
判断对象是否递归
pprint.saferepr(object)
返回对象的字符串表示,如果是递归对象,则用 <Recursion on typename with id=number>替代递归引用。
>>> pprint.saferepr(stuff)
"[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
1.PrettyPrinter对象
PrettyPrinter对象有以下几种方法。
PrettyPrinter.pformat(object)
PrettyPrinter.pprint(object)
PrettyPrinter.isreadable(object)
PrettyPrinter.isrecursive(object)
PrettyPrinter.format(object, context, maxlevels, level)
返回三个参数,一个是格式化字符串,一个判断结果是否可读的标志,一个判断对象是否递归的标志。第一个参数是要格式化输出的对象,
2.pprint示例
2.pprint示例
>>>import pprint
>>> tup =('spam',('eggs',('lumberjack',('knights',('ni',('dead',
...('parrot',('fresh fruit',))))))))
>>> stuff =['a'*10, tup,['a'*30,'b'*30],['c'*20,'d'*20]]
>>> pprint.pprint(stuff)
['aaaaaaaaaa',
('spam',
('eggs',
('lumberjack',
('knights',('ni',('dead',('parrot',('fresh fruit',)))))))),
['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
['cccccccccccccccccccc','dddddddddddddddddddd']]
>>> pprint.pprint(stuff, depth=3)
['aaaaaaaaaa',
('spam',('eggs',(...))),
['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
['cccccccccccccccccccc','dddddddddddddddddddd']]
>>> pprint.pprint(stuff, width=60)
['aaaaaaaaaa',
('spam',
('eggs',
('lumberjack',
('knights',
('ni',('dead',('parrot',('fresh fruit',)))))))),
['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
['cccccccccccccccccccc','dddddddddddddddddddd']]