Python學習筆記字典之漂亮打印pprint模塊


隨筆記錄方便自己和同路人查閱。

#------------------------------------------------我是可恥的分割線-------------------------------------------

  如果程序中倒入pprint模塊,就可以使用pprint()和pformat()函數,它們將“漂亮打印”一個字典的字。如果

想要字典中表項的現實比print()的輸出結果更干凈,這就游泳了。

#------------------------------------------------我是可恥的分割線-------------------------------------------

  1、普通打印,示例代碼1:

count = {}
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
for character in message:
    count.setdefault(character,0)
    count[character] = count[character] +1
print(count)

  運行結果:

 

  2、漂亮打印,示例代碼:

import pprint
count = {}
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
for character in message:
    count.setdefault(character,0)
    count[character] = count[character] +1
pprint.pprint(count)

  運行結果:

  3、如果希望得到漂亮打印的文本作為字符串,而不是顯示在屏幕上,那就調用pprint.format(),示例代碼:

import pprint
count = {}
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
for character in message:
    count.setdefault(character,0)
    count[character] = count[character] +1
#pprint.pprint(count)
print(pprint.pformat(count))

  運行結果:

  根據運行結果可以看出,pprint.pprint(count)和print(pprint.pformat(count))是等價的


免責聲明!

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



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