天天看點

pprint代替print更友好的列印調試資訊超出80字元,列印的元素是換行的正常列印行寬為 20行寬為 70超出的層級會用 ... 表示

pprint 是 “pretty printer” 的簡寫,“pretty” 的含義是 “漂亮的、美觀的”,是以 pprint 的含義便是:漂亮的列印。

這是個相當簡單卻有用的子產品,主要用于列印複雜的資料結構對象,例如多層嵌套的清單、元組和字典等。

先看看 print() 列印的一個例子:

mylist = ["Beautiful is better than ugly.", "Explicit is better than implicit.", "Simple is better than complex.", "Complex is better than complicated."]

print(mylist)

['Beautiful is better than ugly.', 'Explicit is better than implicit.', 'Simple is better than complex.', 'Complex is better than complicated.']

這是一個簡單的例子,全部列印在一行裡。如果對象中的元素是多層嵌套的内容(例如複雜的 字典 資料),再列印出那肯定是一團糟的,不好閱讀。

使用 pprint 子產品的 pprint() 替代 print(),可以解決如下痛點:

設定合适的行寬度,作适當的換行

設定列印的縮進、層級,進行格式化列印

判斷對象中是否有無限循環,并優化列印内容

基本使用

pprint(object, stream=None, indent=1, width=80, depth=None, *,compact=False)

預設的行寬度參數為 80,當列印的字元小于 80 時,pprint() 基本上等同于内置函數 print(),當字元超出時,它會作美化,進行格式化輸出。

import pprint

pprint.pprint(mylist)

超出80字元,列印的元素是換行的

['Beautiful is better than ugly.',

'Explicit is better than implicit.',

'Simple is better than complex.',

'Complex is better than complicated.']

設定縮進

pprint.pprint(mylist, indent=4)

[ 'Beautiful is better than ugly.',

'Explicit is better than implicit.',
'Simple is better than complex.',
'Complex is better than complicated.']           

設定列印行寬

mydict = {'students': [{'name':'Tom', 'age': 18},{'name':'Jerry', 'age': 19}]}

pprint.pprint(mydict)

正常列印

{'students': [{'age': 18, 'name': 'Tom'}, {'age': 19, 'name': 'Jerry'}]}

pprint.pprint(mydict, width=20)

行寬為 20

{'students': [{'age': 18,

'name': 'Tom'},
          {'age': 19,
           'name': 'Jerry'}]}
           

pprint.pprint(mydict, width=70)

行寬為 70

{'students': [{'age': 18, 'name': 'Tom'},

{'age': 19, 'name': 'Jerry'}]}           

設定列印層級

newlist = [1, [2, [3, [4, [5]]]]]

pprint.pprint(newlist, depth=3)

超出的層級會用 ... 表示

[1, [2, [3, [...]]]]

用 pprint 替換 print

print = pprint.pprint

更多用法請檢視官方文檔

總體而言,pprint() 是 print() 的輕量級替代,簡單實用,非常友善,而且還是 Python 标準庫。