Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the pprint of python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

本篇内容介绍了"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)

>>> import pprint

>>> pprint.pprint(p)

beeprint

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

from beeprint import pp

pp(p)

instance(Person):

age: 10

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

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report