08-美观地输出
5.2 美观地输出
如果程序导入了 pprint
模块,就可以使用 pprint()
和 pformat()
函数,它们将“美观地输出”一个字典的字。如果想要字典中项的显示比 print()
函数的输出结果更优雅,该功能就有用了。修改前面的 characterCount.py 程序,将它保存为prettyCharacterCount.py:
import pprint
message = 'It was a bright cold day in April, and the clocks were striking
thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
可以在https://autbor.com/pprint/上查看该程序的执行情况。这一次,当程序运行时,输出结果看起来更优雅,键是排过序的:
{' ': 13,
',': 1,
'.': 1,
'A': 1,
'I': 1,
--snip--
't': 6,
'w': 2,
'y': 1}
如果字典本身包含嵌套的列表或字典,那么 pprint.pprint()
函数就特别有用。
如果希望将美观的文本作为字符串输出,而不显示在屏幕上,那就调用 pprint. pformat()
函数。下面两行代码是等价的:
pprint.pprint(someDictionaryValue)
print(pprint.pformat(someDictionaryValue))