Python3中如何使用pprint打印
小編給大家分享一下Python3中如何使用pprint打印,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
概述
在我們使用內置打印函數print時,打印出的Python數據結構對象總是一行的輸出的方式,這樣對數據結構較復雜或數據較多的對象的顯示并不美觀,這時我們可以利用pprint輸出美化數據結構對象。
pprint方法概覽
美化輸出
我們可以利用pprint中的PrettyPrinter控制輸出的打印時的縮進,行寬、甚至打印深度等,定義類如下class pprint.PrettyPrinter(indent = 1,width = 80,depth = None,stream = None,*,compact = False )
-
indent 縮進
-
width 寬度
-
depth 打印深度
-
stream 指輸出流對象,stream = None輸出流對象默認是sys.stdout
-
compact 如果compact為false(默認值),則長序列中的每個項目將在單獨的行上進行格式化。如果compact為true,則將在每個輸出行上格式化適合寬度的項目。
importpprint L=[str(i)*20foriinrange(10)] pp=pprint.PrettyPrinter(indent=4) pp.pprint(L) print(L)
示例結果:
[ '00000000000000000000',
'11111111111111111111',
'22222222222222222222',
'33333333333333333333',
'44444444444444444444',
'55555555555555555555',
'66666666666666666666',
'77777777777777777777',
'88888888888888888888',
'99999999999999999999']
['00000000000000000000', '11111111111111111111', '22222222222222222222', '33333333333333333333', '44444444444444444444', '55555555555555555555', '66666666666666666666', '77777777777777777777', '88888888888888888888', '99999999999999999999']
對象字符串
我們也可以將目標對象的格式化表示形式返回為字符串。indent,width,depth和compact將PrettyPrinter作為格式化參數傳遞給構造函數,定義類如下
L=[str(i)*20foriinrange(10)] pp=pprint.pformat(L,indent=4) print(pp) print(L)
示例結果:
[ '00000000000000000000',
'11111111111111111111',
'22222222222222222222',
'33333333333333333333',
'44444444444444444444',
'55555555555555555555',
'66666666666666666666',
'77777777777777777777',
'88888888888888888888',
'99999999999999999999']
['00000000000000000000', '11111111111111111111', '22222222222222222222', '33333333333333333333', '44444444444444444444', '55555555555555555555', '66666666666666666666', '77777777777777777777', '88888888888888888888', '99999999999999999999']
格式化打印
輸出格式的對象字符串到指定的輸出流,最后以換行符結束,定義類如下
importpprint L=[str(i)*20foriinrange(10)] pprint.pprint(L,indent=4) print(L)
示例結果:
[ '00000000000000000000',
'11111111111111111111',
'22222222222222222222',
'33333333333333333333',
'44444444444444444444',
'55555555555555555555',
'66666666666666666666',
'77777777777777777777',
'88888888888888888888',
'99999999999999999999']
['00000000000000000000', '11111111111111111111', '22222222222222222222', '33333333333333333333', '44444444444444444444', '55555555555555555555', '66666666666666666666', '77777777777777777777', '88888888888888888888', '99999999999999999999']
可讀性
判斷對象object的字符串對象是否可讀,True可讀,反之則反。
importpprint L=[str(i)*20foriinrange(10)] B=pprint.isreadable(L) print(B)
示例結果:
True
總結
以上是生活随笔為你收集整理的Python3中如何使用pprint打印的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python实现语音播放_用Python
- 下一篇: 什么是json的转义字符