Python模块学习6-pprint
Reading Time:The full text has 391 words, estimated reading time: 2 minutes
Creation Date:2017-08-07
Previous Article:Python模块学习7-random
Next Article:Python模块学习5-itertools
BEGIN
模块说明
pprint模块常用于列表、元组和字典数据类型的美化输出。提供的方法包括有pformat()
、pprint()
和 saferepr()
,其中pprint.pprint()方法最常用,常用来调试,如查看某个特殊对象的内部成员,例,查看math模块的内部成员:pprint.pprint(vars(math))
这个模块还是挺鸡肋的,除了配合ipdb调试的时候会用到其它地方应该不会遇到需要应用的地方。
pprint.pprint()
pprint(object, stream=None, indent=1, width=80, depth=None)
:将对象美化输出,indent设置首行缩进的宽度,depth设置显示显示的对象深度既层级。
输出pprint模块中的所有属性及方法,指定深度为1层。
import pprint
pprint.pprint(vars(pprint), depth=1)
'''
{'PrettyPrinter': <class pprint.PrettyPrinter at 0x7f7746d60808>,
'_StringIO': <built-in function StringIO>,
'__all__': [...],
'__builtins__': {...},
'__doc__': "Support to pretty-print lists, tuples, & dictionaries recursively.\n\nVery simple, but useful, especially in debugging data structures.\n\nClasses\n-------\n\nPrettyPrinter()\n Handle pretty-printing operations onto a stream using a configured\n set of formatting parameters.\n\nFunctions\n---------\n\npformat()\n Format a Python object into a pretty-printed representation.\n\npprint()\n Pretty-print a Python object to a stream [default is sys.stdout].\n\nsaferepr()\n Generate a 'standard' repr()-like value, but protect against recursive\n data structures.\n\n",
'__file__': '/usr/lib/python2.7/pprint.pyc',
'__name__': 'pprint',
'__package__': None,
'_commajoin': <built-in method join of str object at 0x7f7746d705f8>,
'_id': <built-in function id>,
'_len': <built-in function len>,
'_perfcheck': <function _perfcheck at 0x7f7746d779b0>,
'_recursion': <function _recursion at 0x7f7746d77938>,
'_safe_repr': <function _safe_repr at 0x7f7746d77500>,
'_sorted': <function _sorted at 0x7f7746d77488>,
'_sys': <module 'sys' (built-in)>,
'_type': <type 'type'>,
'isreadable': <function isreadable at 0x7f7746d77398>,
'isrecursive': <function isrecursive at 0x7f7746d77410>,
'pformat': <function pformat at 0x7f7746d772a8>,
'pprint': <function pprint at 0x7f7746d77230>,
'saferepr': <function saferepr at 0x7f7746d77320>,
'warnings': <module 'warnings' from '/usr/lib/python2.7/warnings.pyc'>}
'''
pprint.pformat()
pformat(object, indent=1, width=80, depth=None)
:和pprint.pprint()方法的区别在于,pprint方法返回对象,pformat方法返回pprint放回的对象的字符串表示形式。
pprint.saferepr()
saferepr(object)
:将对象转换成字符串,并通过repr方法处理后返回。
FINISH
Previous Article:Python模块学习7-random
Next Article:Python模块学习5-itertools