好程式設計師Python學習路線分享用pprint代替print

好程式設計師IT發表於2019-10-09

好程式設計師Python 學習路線分享 pprint 代替 print 更友好的列印除錯資訊

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

 

這是個相當簡單卻有用的模組,主要用於列印複雜的資料結構物件,例如多層巢狀的列表、元組和字典等。

 

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

 

```python

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() ,可以解決如下痛點:

 

- ** 設定合適的行寬度,作適當的換行 **

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

- ** 判斷物件中是否有無限迴圈,並最佳化列印內容 **

 

基本使用

 

```python

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

```

 

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

 

```python

import pprint

 

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

 

pprint.pprint(mylist)

 

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

['Beautiful is better than ugly.',

 'Explicit is better than implicit.',

 'Simple is better than complex.',

 'Complex is better than complicated.']

```

 

設定縮排

```python

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.']

```

 

設定列印行寬

- ```python

  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'}]}

  ```

 

設定列印層級

```python

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

 

pprint.pprint(newlist, depth=3)

 

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

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

```

 

pprint 替換 print

```python

import pprint

print = pprint.pprint

 

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() print() 的輕量級替代,簡單實用,非常方便,而且還是 Python 標準庫。

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69913892/viewspace-2659220/,如需轉載,請註明出處,否則將追究法律責任。

相關文章