python之pprint模块

学过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']"
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值