python pprint模塊


pprint模塊 提供了打印出任何python數據結構類和方法。

模塊方法:

1.class pprint.PrettyPrinter(indent=1,width=80,depth=None, stream=None)    

   創建一個PrettyPrinter對象

    indent --- 縮進,width --- 一行最大寬度,

    depth --- 打印的深度,這個主要是針對一些可遞歸的對象,如果超出指定depth,其余的用"..."代替。

                 eg: a=[1,2,[3,4,],5]  a的深度就是2; b=[1,2,[3,4,[5,6]],7,8] b的深度就是3

    stream ---指輸出流對象,如果stream=None,那么輸出流對象默認是sys.stdout

2.pprint.pformat(object,indent=1,width=80, depth=None) 

   返回格式化的對象字符串

3.pprint.pprint(object,stream=None,indent=1, width=80, depth=None) 

  輸出格式的對象字符串到指定的stream,最后以換行符結束。

4.pprint.isreadable(object) 

   判斷對象object的字符串對象是否可讀

5.pprint.isrecursive(object) 

   判斷對象是否需要遞歸的表示

   eg: pprint.isrecursive(a)  --->False

        pprint.isrecursive([1,2,3])-->True

6.pprint.saferepr(object) 

   返回一個對象字符串,對象中的子對象如果是可遞歸的,都被替換成<Recursionontypename withid=number>.這種形式。

 

PrettyPrinter 對象具有的方法與上面類似,不在贅述。

import pprint

data = (
"this is a string", [1, 2, 3, 4], ("more tuples",
1.0, 2.3, 4.5), "this is yet another string"
)

pprint.pprint(data)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM