title: pprint的使用
date: 2020-12-01 22:15:45
tags: Python的使用
pprint是"pretty printer"的缩写,主要是用于替代print()打印复杂的数据结构对象,并且从英文全称就可以很明白地知道了这个库函数就是为了美化打印。
pprint主要的作用:
- 设置打印的缩进、层级、并且进行格式化打印
- 设置适合的行宽度,并且作适当的换行。
- 判断对象中是否有无限循环,并循环打印。
1.简单使用
我们使用pprint库来调用pprint。
pprint(object, stream=None, indent=1, width=80, depth=None, compact=False)
# object->对象
# stream->设置输出流,模块中默认使用sys.stdout。该对象唯一会使用到的函数是write()
# ident->缩进,默认为1
# width->宽度
# depth->打印出的层级,超过则以...显示
# compact->如果值为False,超过width规定长度的序列会被分散打印到多行。如果为True,会尽量使序列填满width规定的宽度。
import pprint
mylist = ["Are you OK?", "Are you real OK?", "Go ahead!", "Simple is better than complex."]
print(mylist)
pprint.pprint(mylist)
输出:
['Are you OK?', 'Are you real OK?', 'Go ahead!', 'Simple is better than complex.']
['Are you OK?',
'Are you real OK?',
'Go ahead!',
'Simple is better than complex.']
可以看出pprint的输出明显比print的美观许多。
2.设置缩进为3的空格
import pprint
mylist = ["Are you OK?", "Are you real OK?", "Go ahead!", "Simple is better than complex."]
pprint