pprint 模块(漂亮打印器)


pprint 模块 (lib/pprint.py) 是 Python 标准库的一部分,与标准 Python 发行版一起分发。pprint 代表漂亮打印器 (pretty printer)。pprint 模块的功能使 Python 数据结构的外观更美观。任何可以被 Python 解释器正确解析的数据结构都可以被优雅地格式化。格式化的表达式尽可能保持在一行,但如果长度超过格式化的 width 参数,则会分成多行。pprint 输出的一个独特之处在于,字典在显示表示形式被格式化之前会自动排序。

pprint 模块包含 PrettyPrinter 类的定义。其构造函数采用以下格式:

pprint.PrettyPrinter(indent, width, depth, stream, compact)

indent 参数定义每个递归级别添加的缩进。默认为 1。

width 参数默认为 80。期望的输出受此值限制。如果长度大于 width,则会分成多行。

depth 参数控制要打印的级别数。

stream 参数默认为 std.out——默认输出设备。它可以采用任何流对象,例如文件。

compact 参数默认为 False。如果为 True,则只显示可在 width 内调整的数据。

PrettyPrinter 类定义了以下方法:

**pprint()** - 打印 PrettyPrinter 对象的格式化表示

**pformat()** - 返回对象的格式化表示,基于构造函数的参数。

以下示例演示了 PrettyPrinter 类的简单用法。

import pprint
students = {"Dilip":["English", "Maths", "Science"],
   "Raju":{"English":50,"Maths":60, "Science":70},
   "Kalpana":(50,60,70)}
pp = pprint.PrettyPrinter()
print ("normal print output")
print (students)
print ("----")
print ("pprint output")
pp.pprint(students)

输出显示了普通打印和漂亮打印。

normal print output
{'Dilip': ['English', 'Maths', 'Science'], 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}, 'Kalpana': (50, 60, 70)}
----
pprint output
{'Dilip': ['English', 'Maths', 'Science'],
'Kalpana': (50, 60, 70),
'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

pprint 模块还定义了与 PrettyPrinter 方法对应的便利函数 pprint() 和 pformat()。下面的示例使用了 pprint() 函数。

from pprint import pprint
students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
print ("normal print output")
print (students)
print ("----")
print ("pprint output")
pprint (students)

下一个示例使用 pformat() 方法和 pformat() 函数。要使用 pformat() 方法,首先要设置 PrettyPrinter 对象。在这两种情况下,格式化的表示都使用普通的 print() 函数显示。

import pprint
students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
print ("using pformat method")
pp = pprint.PrettyPrinter()
string = pp.pformat(students)
print (string)
print ('------')
print ("using pformat function")
string = pprint.pformat(students)
print (string)

以下是上述代码的输出

using pformat method
{'Dilip': ['English', 'Maths', 'Science'],
'Kalpana': (50, 60, 70),
'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}
------
using pformat function
{'Dilip': ['English', 'Maths', 'Science'],
'Kalpana': (50, 60, 70),
'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

漂亮打印器也可以与自定义类一起使用。在类中重写了 __repr__() 方法。当使用 repr() 函数时,会调用 __repr__() 方法。它是 Python 对象的官方字符串表示。当我们使用对象作为 print() 函数的参数时,它会打印 repr() 函数的返回值。

在下面的示例中,__repr__() 方法返回 player 对象的字符串表示

import pprint
class player:
def __init__(self, name, formats = [], runs = []):
self.name = name
self.formats = formats
self.runs = runs
def __repr__(self):
dct = {}
dct[self.name] = dict(zip(self.formats,self.runs))
return (repr(dct))
l1 = ['Tests','ODI','T20']
l2 = [[140, 45, 39],[15,122,36,67, 100, 49],[78,44, 12, 0, 23, 75]]
p1 = player("virat",l1,l2)
pp = pprint.PrettyPrinter()
pp.pprint(p1)

上述代码的输出为:

{'virat': {'Tests': [140, 45, 39], 'ODI': [15, 122, 36, 67, 100, 49], 'T20': [78, 44, 12, 0, 23, 75]}}

使用 pprint 处理递归数据结构

当我们尝试使用 pprint 打印递归对象时,只显示第一个表示,对于后续的递归,只打印其引用。

>>> import pprint
>>> numbers = list(range(1,6))
>>> numbers.append(numbers)
>>> print (numbers)
[1, 2, 3, 4, 5, [...]]
>>> pprint.pprint(numbers)
[1, 2, 3, 4, 5, <Recursion on list with id=1403633698824>]

限制输出宽度

如果将 width 参数从默认的 80 更改为其他值,则输出将以多行显示的方式进行格式化,同时注意不要违反语法。

import pprint
students = {"Dilip":["English", "Maths", "Science"],
"Raju":{"English":50,"Maths":60, "Science":70},
"Kalpana":(50,60,70)}
pp=pprint.PrettyPrinter(width = 20)
pp.pprint(students)

此代码与本文中的第一个示例类似。但是,PrettyPrinter 对象是用 width 参数为 20 构造的。因此,pprint 输出相应地进行了格式化。

{'Dilip': [ 'English',
   'Maths',
   'Science'],
'Kalpana': (50,
   60,
   70),
'Raju': {'English': 50,
   'Maths': 60,
   'Science': 70}}

更新于:2020年6月27日

1K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.