在我们使用内置打印函数print时,打印出的Python数据结构对象总是一行的输出的方式,这样对数据结构较复杂或数据较多的对象的显示并不美观,这时我们可以利用pprint输出美化数据结构对象。
我们可以利用pprint中的PrettyPrinter控制输出的打印时的缩进,行宽、甚至打印深度等,定义类如下class pprint.PrettyPrinter(indent = 1,width = 80,depth = None,stream = None,*,compact = False )
stream = None输出流对象默认是sys.stdout
import pprint
L = [str(i)*20 for i in range(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 作为格式化参数传递给构造函数,定义类如下pprint.pformat(*object*,*indent = 1*,*width = 80*,*depth = None*,***,*compact = False *)[¶](https://docs.python.org/zh-cn/3.7/library/pprint.html#pprint.pformat "永久链接至目标")
L = [str(i)*20 for i in range(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']
输出格式的对象字符串到指定的输出流,最后以换行符结束,定义类如下pprint.pprint(object,stream = None,indent = 1,width = 80,depth = None,*,compact = False )
import pprint
L = [str(i)*20 for i in range(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可读,反之则反。
import pprint
L = [str(i)*20 for i in range(10)]
B = pprint.isreadable(L)
print(B)
示例结果:
True
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3112/viewspace-2822998/ ,如需转载,请注明出处,否则将追究法律责任。