1.整體設置
- 對2-5的打印有一個整個變量的聲明以及賦值,下面2-5的輸出都是針對他的輸出
#變量的賦值
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)
}
]
2.print
一般我們學一門編程語言最開始學的就是打印函數,因爲把變量的值直接打印出來這是一個瞭解變量信息最直觀的感受。但是print的特點是對打印信息不做格式的整理,只是無腦一行輸出,所以對於那些複雜的變量理解性就很差,並且對於對象也只是將其地址輸出
-
程序實例:
print(coordinates)
3.內置更強大的pprint
不過需要導入模塊import pprint
,該打印方法能夠對格式進行整理同時還可以指定長寬(專業定製是不是很炫酷),但是依舊對類沒有相應屬性的輸出,所以當我們不需要對象屬性輸出的時候可以考慮使用它,但是需要對象屬性輸出的時候就應該考慮第三種安裝第三方庫的方法。
-
程序實例:
pp = pprint.PrettyPrinter(indent=4, width=50)# 指定縮進和寬度 pp.pprint(coordinates) # 2.1、pprint打印類(打印類的時候不是很優雅,直接出的地址——地址誰看得懂,即使看懂也比較費時費力) class Person(): def __init__(self, age): self.age = age p = Person(10) print("=========================================================\n The second_three way to print:pprint.pprint(p)") pprint.pprint(p)
4.最爲優雅的pp
輸出方案
由於自帶的庫沒有支持輸出對象屬性的方法,所以需要第三方庫beeprint
支持,beeprint
自帶的pp方法不僅可以打印實現格式的整理還可以實現對象屬性的輸出
-
程序實例:
p = Person(10) from beeprint import pp print("=========================================================\n The thrnd way to print:pp(p)") pp(p)
5.輸出結果顯示
=========================================================
The first way to print:print
[{'name': 'Location 1', 'gps': (29.008966, 111.573724)}, {'name': 'Location 2', 'gps': (40.1632626, 44.2935926)}, {'name': 'Location 3', 'gps': (29.476705, 121.869339)}]
=========================================================
The second_one way to print: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'}]
=========================================================
The second_two way to print: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'}]
=========================================================
The second_three way to print:pprint.pprint(p)
<__main__.Person object at 0x0000020EDCC52C10>
=========================================================
The thrnd way to print:pp(p)
instance(Person):
age: 10