![52806eb65aa8ea39cd677128b814c861.png](https://i-blog.csdnimg.cn/blog_migrate/3009d25c6e59c5e8df90793bc405dddb.jpeg)
pprint 是“pretty printer”的简写, 主要用于替代 print() 打印复杂的数据结构对象:
- 设置合适的行宽度,作适当的换行
- 设置打印的缩进、层级,进行格式化打印
- 判断对象中是否有无限循环,并优化打印内容
1. 简单使用
pprint
默认的行宽度参数为 80,当打印的字符(character)小于 80 时,pprint() 基本上等同于内置函数 print(),当字符超出时,它会作美化,进行格式化输出:
import
输出:
['Beautiful is better than ugly.', 'Explicit is better than implicit.', 'Simple is better than complex.', 'Complex is better than complicated.']
['Beautiful is better than ugly.',
'Explicit is better than implicit.',
'Simple is better than complex.',
'Complex is better than complicated.']
2. 设置缩进为 4 个空格(默认为1)
import
输出:
[ 'Beautiful is better than ugly.',
'Explicit is better than implicit.',
'Simple is better than complex.',
'Complex is better than complicated.']
3. 设置打印的行宽
import
输出:
{'students': [{'age': 18, 'name': 'Tom'}, {'age': 19, 'name': 'Jerry'}]}
{'students': [{'age': 18,
'name': 'Tom'},
{'age': 19,
'name': 'Jerry'}]}
{'students': [{'age': 18, 'name': 'Tom'},
{'age': 19, 'name': 'Jerry'}]}
4. 设置打印的层级(默认全打印)
import
输出:
[1, [2, [3, [...]]]]
5. 优化循环结构的打印
import
输出:
[[...], 1, 2]
[<Recursion on list with id=1995468111360>, 1, 2]
6. 判断是否出现循环结构
import
输出:
True
False
isreadable() 除了能像 isrecursive() 一样判断循环,还能判断该格式化内容是否可被 eval() 重构。