安裝
pip install pprint
pprint提供了以一種“pretty-print”的方式打印出任意python數據結構的模塊。當然,如果不是python的基本數據類型,那麼這種方式可能加載不出來。簡單來講,就是一種打印方式。
如果可以的話,將對象保留在一行上,如果寬度不合適,那麼將它們分成多行。 需要調整寬度的話,構建PrettyPrinter對象。
模塊方法:
class PrettyPrinter:
def __init__(self, indent=1, width=80, depth=None, stream=None, *,
compact=False):
- indent: 縮進,默認爲1
- width:寬度
- depth:深度
打印的深度,這個主要是針對一些可遞歸的對象,如果超出指定depth,其餘的用"…"代替。
eg: a=[1,2,[3,4,],5] a的深度就是2; b=[1,2,[3,4,[5,6]],7,8] b的深度就是3
- stream: 指輸出流對象,如果stream=None,那麼輸出流對象默認是sys.stdout
- compact 如果compact爲false(默認值),則長序列中的每個項目將在單獨的行上進行格式化。如果compact爲true,則將在每個輸出行上格式化適合寬度的項目。
pprint.pformat(object,indent=1,width=80, depth=None)
返回格式化的對象字符串
pprint.pprint(object,stream=None,indent=1, width=80, depth=None)
輸出格式的對象字符串到指定的stream,最後以換行符結束。
pprint.isreadable(object)
判斷對象object的字符串對象是否可讀
pprint.isrecursive(object)
判斷對象是否需要遞歸的表示
eg: pprint.isrecursive(a) --->False
pprint.isrecursive([1,2,3])-->True
pprint.saferepr(object)
返回一個對象字符串,對象中的子對象如果是可遞歸的,都被替換成.這種形式。
>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter() #採用默認值
>>> pp.pprint(stuff)
[['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
'spam',
'eggs',
'lumberjack',
'knights',
'ni']
>>> pp = pprint.PrettyPrinter(indent=4) #縮進爲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) #深度爲6,所有隻顯示了6層
>>> pp.pprint(tup)('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
#2、格式化
data = [(1,{'a':'A','b':'B','c':'C','d':'D'}),(2,{'e':'E','f':'F','g':'G','h':'H','i':'I','j':'J','k':'K','l':'L'}),]
result=pprint.pformat(data)
for key in result.splitlines():
print key
'''
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
(2,
{'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L'})]
'''
還有一些其他方法,可以參考官方文檔說明:
https://docs.python.org/2/library/pprint.html#module-pprint
參考:https://blog.csdn.net/Lisa_Ren_123/article/details/80206898
https://www.cnblogs.com/linwenbin/p/10777736.html
https://www.zhangshengrong.com/p/q0Xpqgb61K/