Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
286
|
8 章 字串類的東西
pprint 模組
pprint
模組能夠美觀地印出(pretty-prints)複雜的資料結構,致力於提供
比內建的
repr
函式(涵蓋於表 7-2)所能提供的更容易閱讀的格式。要微
調格式化的方式,你可以實體化
pprint
所提供的
PrettyPrinter
類別,再
套用詳細的控制,並由同樣也是
pprint
提供的輔助函式來協助。然而,多
數時候,
pprint
對外提供的兩個主要函式之一就足夠了:
pformat pformat(obj)
回傳代表
obj
美觀印出結果的一個字串。
pprint pprint(obj,stream=sys.stdout)
obj
的美觀印出結果輸出到開啟來寫入的檔案物件
stream
,結尾帶有一個
newline
下列述句所做的事情完全相同:
print(pprint.pformat(x))
pprint.pprint(x)
在許多情況下,這些構造都大略等同於
print(x)
,例如當
x
的字串表示值
string representation)能完全放入單一個文字行之時。然而,使用像是
x=list(range(30))
這樣的東西時,
print(x)
會以兩行顯示
x
,斷在任意的點,
而使用模組
pprint
則會以超過 30 行顯示
x
,一行一個項目。你可以在你偏好
該模組的特定顯示效果時使用
pprint
,而非一般的字串表示值。
reprlib 模組
reprlib
模組(在 v2 中名為
repr
)提供內建函式
repr
(涵蓋於表 7-2)的
一種替代選擇,它會限制表
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819