溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

python的pprint怎么用

發(fā)布時(shí)間:2022-01-17 15:53:07 來(lái)源:億速云 閱讀:288 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“python的pprint怎么用”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

學(xué)python學(xué)到的第一個(gè)函數(shù)就是print

print("hello world")

不管是新手還是老手,都會(huì)經(jīng)常用來(lái)調(diào)試代碼。但是對(duì)于稍微復(fù)雜的對(duì)象,打印出來(lái)就的時(shí)候可讀性就沒(méi)那么好了。

例如:

>>> coordinates = [
...    {
...        "name": "Location 1",
...        "gps": (29.008966, 111.573724)
...    },
...    {
...        "name": "Location 2",
...        "gps": (40.1632626, 44.2935926)
...    },
...    {
...        "name": "Location 3",
...        "gps": (29.476705, 121.869339)
...    }
... ]

>>> print(coordinates)
[{'name': 'Location 1', 'gps': (29.008966, 111.573724)}, {'name': 'Location 2', 'gps': (40.1632626, 44.2935926)}, {'name': 'Location 3', 'gps': (29.476705, 121.869339)}]
>>>

打印一個(gè)很長(zhǎng)的列表時(shí),全部顯示在一行,兩個(gè)屏幕都裝不下。

于是 pprint 出現(xiàn)了

pprint

pprint 的全稱(chēng)是Pretty Printer,更美觀的 printer。在打印內(nèi)容很長(zhǎng)的對(duì)象時(shí),它能夠以一種格式化的形式輸出。

>>> import pprint
>>> pprint.pprint(coordinates)
[{'gps': (29.008966, 111.573724), 'name': 'Location 1'},
{'gps': (40.1632626, 44.2935926), 'name': 'Location 2'},
{'gps': (29.476705, 121.869339), 'name': 'Location 3'}]
>>>

當(dāng)然,你還可以自定義輸出格式

# 指定縮進(jìn)和寬度
>>> pp = pprint.PrettyPrinter(indent=4, width=50)
>>> pp.pprint(coordinates)
[   {   'gps': (29.008966, 111.573724),
       'name': 'Location 1'},
   {   'gps': (40.1632626, 44.2935926),
       'name': 'Location 2'},
   {   'gps': (29.476705, 121.869339),
       'name': 'Location 3'}]

但是pprint還不是很優(yōu)雅,因?yàn)榇蛴∽远x的類(lèi)時(shí),輸出的是對(duì)象的內(nèi)存地址相關(guān)的一個(gè)字符串

class Person():
   def __init__(self, age):
       self.age = age

p = Person(10)

>>> print(p)
<__main__.Person object at 0x00BCEBD0>
>>> import pprint
>>> pprint.pprint(p)
<__main__.Person object at 0x00BCEBD0>

beeprint

而用beeprint可以直接打印對(duì)象里面的屬性值,省去了重寫(xiě) __str__  方法的麻煩

from beeprint import pp
pp(p)
instance(Person):
 age: 10

不同的是,print和pprint是python的內(nèi)置模塊,而 beeprint 需要額外安裝。

“python的pprint怎么用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI