python的pprint怎么用

发布时间:2022-01-17 15:53:07 作者:iii
来源:亿速云 阅读:296

本篇内容介绍了“python的pprint怎么用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

学python学到的第一个函数就是print

print("hello world")

不管是新手还是老手,都会经常用来调试代码。但是对于稍微复杂的对象,打印出来就的时候可读性就没那么好了。

例如:

>>> coordinates = [
...    {
...        "name": "Location 1",
...        "gps": (29.008966, 111.573724)
...    },
...    {
...        "name": "Location 2",
...        "gps": (40.1632626, 44.2935926)
...    },
...    {
...        "name": "Location 3",
...        "gps": (29.476705, 121.869339)
...    }
... ]

>>> print(coordinates)
[{'name': 'Location 1', 'gps': (29.008966, 111.573724)}, {'name': 'Location 2', 'gps': (40.1632626, 44.2935926)}, {'name': 'Location 3', 'gps': (29.476705, 121.869339)}]
>>>

打印一个很长的列表时,全部显示在一行,两个屏幕都装不下。

于是 pprint 出现了

pprint

pprint 的全称是Pretty Printer,更美观的 printer。在打印内容很长的对象时,它能够以一种格式化的形式输出。

>>> import pprint
>>> pprint.pprint(coordinates)
[{'gps': (29.008966, 111.573724), 'name': 'Location 1'},
{'gps': (40.1632626, 44.2935926), 'name': 'Location 2'},
{'gps': (29.476705, 121.869339), 'name': 'Location 3'}]
>>>

当然,你还可以自定义输出格式

# 指定缩进和宽度
>>> pp = pprint.PrettyPrinter(indent=4, width=50)
>>> pp.pprint(coordinates)
[   {   'gps': (29.008966, 111.573724),
       'name': 'Location 1'},
   {   'gps': (40.1632626, 44.2935926),
       'name': 'Location 2'},
   {   'gps': (29.476705, 121.869339),
       'name': 'Location 3'}]

但是pprint还不是很优雅,因为打印自定义的类时,输出的是对象的内存地址相关的一个字符串

class Person():
   def __init__(self, age):
       self.age = age

p = Person(10)

>>> print(p)
<__main__.Person object at 0x00BCEBD0>
>>> import pprint
>>> pprint.pprint(p)
<__main__.Person object at 0x00BCEBD0>

beeprint

而用beeprint可以直接打印对象里面的属性值,省去了重写 __str__  方法的麻烦

from beeprint import pp
pp(p)
instance(Person):
 age: 10

不同的是,print和pprint是python的内置模块,而 beeprint 需要额外安装。

“python的pprint怎么用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. 怎么用python的pip
  2. python pprint模块中print()和pprint()两者的区别有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python pprint

上一篇:python字符串驻留是什么

下一篇:Java中super关键字的用法和细节是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》