學(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 需要額外安裝。