打印,是所有程序员从小白时期就具备的神技,遇事不决打印一下,是 DEBUG 最简单且不依赖 IDE 的方式,自定义各种日志输出,也是项目成型后必备功能。
但是为了优雅的打印格式,往往需要对各种对象进行特殊格式化,可遇到字典和大段字符串也不好处理。
这篇文章介绍两个库模块,可以快速有效的解决所有 Python 对象的打印输出,没错,所有。

pprint

这是 Python 标准库模块,全称 pretty printer,可以让各种数据结构更美观地输出。

>>> print(game)
{'players': [{'name': 'player_1', 'hp': 3}, {'name': 'player_2', 'hp': 5}]}
>>> pprint.pprint(game, width=4)
{'players': [{'hp': 3,
'name': 'player_1'},
{'hp': 5,
'name': 'player_2'}]}

pprint.pprint(objectstream=Noneindent=1width=80depth=None*compact=False)

  • stream:输出流,默认是 sys.stdout ,也就是屏幕输出。
  • indent:缩进空格数。
  • width:每行最大宽度,默认为80个字符,超过宽度会换行,但如果单个对象超过不会被换行,比如一段长字符串。
  • depth:限制数据的层级,设置后可以限制过多的嵌套。
  • compact:3.4版本新加入的参数,若设为 True ,则输出会在接近 width 限制才进行换行。
>>> pprint.pprint(stuff, indent=4)
[ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
'spam',
'eggs',
'lumberjack',
'knights',
'ni']
>>> pprint.pprint(stuff, width=41, compact=True)
[['spam', 'eggs', 'lumberjack',
'knights', 'ni'],
'spam', 'eggs', 'lumberjack', 'knights',
'ni']

pprint.pformat(objectindent=1width=80depth=None*compact=False)

和 pprint.pprint 的区别是,该函数不会打印到输出流,而是返回一个格式化字符串。

>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff)
>>> pprint.pprint(stuff)
[<Recursion on list with id=...>,
'spam',
'eggs',
'lumberjack',
'knights',
'ni']

classpprint.PrettyPrinter(indent=1width=80depth=Nonestream=None*compact=False)

上文两个函数,实际都是构建一个 PrettyPrinter 对象,并调用对应的方法,所以当需要复用格式化的时候,我们可以提前构建该对象。

>>> pp = pprint.PrettyPrinter(width=40, compact=True)
>>> pp.pprint(game)
{'players': [{'hp': 3,
'name': 'player_1'},
{'hp': 5,
'name': 'player_2'}]}
>>> pp.pprint(stuff)
['spam', 'eggs', 'lumberjack',
'knights', 'ni']

更多用法可以参考官方文档:

8.11. pprint - Data pretty printer - Python 3.5.6 documentation​docs.python.org


pprint 对字典 列表这类数据结构确实很好用,但遇到类、字符串仍然和 print 差别不大,因此这里有一个国人写的第三方库介绍给大家。

beeprint

除了和 pprint 一样支持 dict, list, tuple 等常规变量的格式化输出,还支持 object 变量打印、长文本自动剪切。

下面是作者 README 中和 pprint 的对比:

pprint:

{'entities': {'hashtags': [],
'urls': [{'display_url': 'tumblr.com/xnr37hf0yz',
'expanded_url': 'http://tumblr.com/xnr37hf0yz',
'indices': [107, 126],
'url': 'http://t.co/cCIWIwg'}],
'user_mentions': []}}

beeprint:

{
'entities': {
'hashtags': [],
'urls': [
{
'display_url': 'tumblr.com/xnr37hf0yz',
'expanded_url': 'http://tumblr.com/xnr37hf0yz',
'indices': [107, 126],
'url': 'http://t.co/cCIWIwg',
},
],
'user_mentions': [],
},
}

pprint:

<class 'definition.NormalClassNewStyle'>

beeprint:

class(NormalClassNewStyle):
dicts: {
},
lists: [],
static_props: 1,
tuple: (1, 2)

pprint:

<definition.NormalClassNewStyle object at 0x7f338e5a9dd0>

beeprint:

instance(NormalClassNewStyle):
dicts: {
},
lists: [],
say_hi: 'hello world',
static_props: 1,
tuple: (1, 2)

pprint:

[['\nThe sky and the earth were at first one blurred entity like an egg. Pangu was born into it.\n \n\tThe separation of the sky and the earth took eighteen thousand years-the yang which was light and pure rose to become the sky, \tand the yin which was heavy and murky\xef\xbc\x88\xe6\x9c\xa6\xe8\x83\xa7\xe7\x9a\x84\xef\xbc\x89 sank to form the earth. Between them was Pangu, who went through nine \tchanges every day, his wisdom greater than that of the sky and his ability greater than that of the earth. Every day the sky rose ten feet higher, the earth became ten feet thicker, and Pangu grew ten feet taller.\n \nAnother eighteen thousand years passed, and there was an extremely high sky, an extremely thick earth, and an extremely tall Pangu. After Pangu died, his head turned into the Five Sacred Mountains (Mount Tai, Mount Heng, Mount Hua, Mount Heng, Mount Song), his eyes turned into the moon and the sun, his blood changed into water in river and sea, his hair into grass.\n \nIn all, the universe and Pangu combine in one.\n',
'\n\xe6\x8d\xae\xe6\xb0\x91\xe9\x97\xb4\xe7\xa5\x9e\xe8\xaf\x9d\xe4\xbc\xa0\xe8\xaf\xb4\xe5\x8f\xa4\xe6\x97\xb6\xe7\x9b\x98\xe5\x8f\xa4\xe7\x94\x9f\xe5\x9c\xa8\xe9\xbb\x91\xe6\x9a\x97\xe5\x9b\xa2\xe4\xb8\xad\xef\xbc\x8c\xe4\xbb\x96\xe4\xb8\x8d\xe8\x83\xbd\xe5\xbf\x8d\xe5\x8f\x97\xe9\xbb\x91\xe6\x9a\x97\xef\xbc\x8c\xe7\x94\xa8\xe7\xa5\x9e\xe6\x96\xa7\xe5\x8a\x88\xe5\x90\x91\xe5\x9b\x9b\xe6\x96\xb9\xef\xbc\x8c\xe9\x80\x90\xe6\xb8\x90\xe4\xbd\xbf\xe5\xa4\xa9\xe7\xa9\xba\xe9\xab\x98\xe8\xbf\x9c\xef\xbc\x8c\xe5\xa4\xa7\xe5\x9c\xb0\xe8\xbe\xbd\xe9\x98\x94\xe3\x80\x82\n\t\xe4\xbb\x96\xe4\xb8\xba\xe4\xb8\x8d\xe4\xbd\xbf\xe5\xa4\xa9\xe5\x9c\xb0\xe4\xbc\x9a\xe9\x87\x8d\xe6\x96\xb0\xe5\x90\x88\xe5\xb9\xb6\xef\xbc\x8c\xe7\xbb\xa7\xe7\xbb\xad\xe6\x96\xbd\xe5\xb1\x95\xe6\xb3\x95\xe6\x9c\xaf\xe3\x80\x82\xe6\xaf\x8f\xe5\xbd\x93\xe7\x9b\x98\xe5\x8f\xa4\xe7\x9a\x84\xe8\xba\xab\xe4\xbd\x93\xe9\x95\xbf\xe9\xab\x98\xe4\xb8\x80\xe5\xb0\xba\xef\xbc\x8c\xe5\xa4\xa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91\xe6\x97\x8f\xe5\xb4\x87\xe6\x8b\x9c\xe7\x9a\x84\xe8\x8b\xb1\xe9\x9b\x84\xe3\x80\x82\n']]

beeprint:

[
[
'\nThe sky and the earth were at first one blurred entity like an egg. Pangu
was born into it.\n \n\tThe separation of the sky and the earth took
...(12 hidden lines)',
'\n据民间神话传说古时盘古生在黑暗团中,他不能忍受黑暗,用神斧劈向四方,逐渐
使天空高远,大地辽阔。\n\t他为不使天地会重新合并,继续施展法术。每当盘古的
...(3 hidden lines)',
],
]

beeprint.pp(o, output=True, max_depth=5, indent=2, width=80, sort_keys=True, config=None, **kwargs):

参数和 pprint 类似,多出了 sort_keys可以打印字典时是否按 key 排序( pprint 是默认排序,不可选),另外还有控制文本裁剪等行为的参数,可以从 beeprint.Config 里查看。

该库的 Github:https://github.com/panyanyany/beeprint

欢迎关注

微信公众号:面向人生编程

编程思维不应只存留在代码之中,更应伴随于整个人生旅途,这个公众号不只聊技术,还会聊产品/互联网/经济学等广泛话题,所以也欢迎非程序员关注。

打印 Python 的一切 —— pprint & beeprint的更多相关文章

  1. Python 标准库 -> Pprint 模块 -> 用于打印 Python 数据结构

    使用 pprint 模块 pprint 模块( pretty printer ) 用于打印 Python 数据结构. 当你在命令行下打印特定数据结构时你会发现它很有用(输出格式比较整齐, 便于阅读). ...

  2. python之模块pprint之常见用法

    # -*- coding: cp936 -*- #python 27 #xiaodeng #python之模块pprint之常见用法 import pprint data = [(1,{'a':'A' ...

  3. 如何美观地打印 Python 对象?这个标准库可以简单实现

    前不久,我写了一篇文章回顾 Python 中 print 的发展历史 ,提到了两条发展线索: 明线:早期的 print 语句带有 C 和 Shell 的影子,是个应用程序级的 statement,在最 ...

  4. 矩阵按对角线打印---python

    将一个矩阵(二维数组)按对角线向右进行打印.(搜了一下发现好像是美团某次面试要求半小时手撕的题)Example:Input:[[1,2,3,4],[5,1,2,3],[9,5,1,2]]Output: ...

  5. 一行代码打印python之禅

    就这一句: import this 输出: The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is be ...

  6. boost中打印python中的变量

    p::extract<char const *>(p::str(py_variable))

  7. 打印python的堆栈stack

    import sys def pstack(depth = 0): frame = sys._getframe(depth) cnt = 0 while frame: print "###& ...

  8. python pprint

    使用 pprint 模块 pprint 模块( pretty printer ) 用于打印 Python 数据结构. 当你在命令行下打印特定数据结构时你会发现它很有用(输出格式比较整齐, 便于阅读). ...

  9. Python中的输入(input)和输出打印

    目录 最简单的打印 打印数字 打印字符 字符串的格式化输出 python中让输出不换行 以下的都是在Python3.X环境下的 使用 input 函数接收用户的输入,返回的是 str 字符串 最简单的 ...

随机推荐

  1. python __new__ __init__ 区别

    参数 __new__的第一个占位参数是class对象 __init__的第一个占位参数是class的实例对象 其他的参数应一致 作用 __new__ 用来创建实例,在返回的实例上执行__init__, ...

  2. 转 PHP函数---$_Get()和$_Post()的用法

    一.$_Get()和$_Post()函数是用来传值的,即对应两种提交表单的方法,get和post. 二.$_Get方法 (1)获取通过URL的传值 Example 1 新建两个PHP文件,1.php, ...

  3. 088 Merge Sorted Array 合并两个有序数组

    给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1中,使得 num1 成为一个有序数组.注意:你可以假设 nums1有足够的空间(空间大小大于或等于m + n)来保存 ...

  4. 03.Javascript——入门一些方法记录之Map和Set

    JavaScript的默认对象表示方式{}可以视为其他语言中的Map或Dictionary的数据结构,即一组键值对. 但是JavaScript的对象有个小问题,就是键必须是字符串.但实际上Number ...

  5. cucumber 背景和场景的区别

    背景是公用的,每个场景都会执行,相当于前提条件: 场景是一个单独的case 别人的cucumber学习总结: 链接:http://ruby-china.org/topics/7119

  6. 修改Magento默认Export Customers功能

    Magento 1.x的Export功能可以很方便地对Customers的数据进行导出,但是存在几个不足(或者说不方便)的地方: 1. 默认导出的 .CSV文件是以UTF-8格式编码的,而MS Exc ...

  7. Objective-C Fast Enumeration

    Fast enumeration is an Objective-C's feature that helps in enumerating through a collection. So in o ...

  8. 在线matlab网站

    网址: http://octave-online.net/ 使用:

  9. DRP项目

    DRP(distribution resource planning)分销资源计划是管理企业的分销网络的系统,目的是使企业具有对订单和供货具有快速反应和持续补充库存的能力.解决了随着企业销售规模的逐渐 ...

  10. Mysql 主备配置

    来自:http://blog.csdn.net/u013256816/article/details/52536283 1. 了解主备配置过程原理. http://blog.csdn.net/u013 ...