python pprint_python 美化打印: pprint()

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-24 07:13   57   0

52806eb65aa8ea39cd677128b814c861.png

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() 重构。
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP