print比你更好的还有pprint和beeprint

1.整体设置

  • 对2-5的打印有一个整个变量的声明以及赋值,下面2-5的输出都是针对他的输出
#变量的赋值
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)
    }
]

2.print

一般我们学一门编程语言最开始学的就是打印函数,因为把变量的值直接打印出来这是一个了解变量信息最直观的感受。但是print的特点是对打印信息不做格式的整理,只是无脑一行输出,所以对于那些复杂的变量理解性就很差,并且对于对象也只是将其地址输出

  • 程序实例:

    print(coordinates)
    

3.内置更强大的pprint

不过需要导入模块import pprint,该打印方法能够对格式进行整理同时还可以指定长宽(专业定制是不是很炫酷),但是依旧对类没有相应属性的输出,所以当我们不需要对象属性输出的时候可以考虑使用它,但是需要对象属性输出的时候就应该考虑第三种安装第三方库的方法。

  • 程序实例:

    pp = pprint.PrettyPrinter(indent=4, width=50)# 指定缩进和宽度
    pp.pprint(coordinates)
    # 2.1、pprint打印类(打印类的时候不是很优雅,直接出的地址——地址谁看得懂,即使看懂也比较费时费力)
    class Person():
        def __init__(self, age):
            self.age = age
    
    p = Person(10)
    print("=========================================================\n The second_three way to print:pprint.pprint(p)")
    pprint.pprint(p)
    

4.最为优雅的pp输出方案

由于自带的库没有支持输出对象属性的方法,所以需要第三方库beeprint支持,beeprint自带的pp方法不仅可以打印实现格式的整理还可以实现对象属性的输出

  • 程序实例:

    p = Person(10)
    from beeprint import pp
    print("=========================================================\n The thrnd way to print:pp(p)")
    pp(p)
    
    

5.输出结果显示

=========================================================
 The first way to print:print
[{'name': 'Location 1', 'gps': (29.008966, 111.573724)}, {'name': 'Location 2', 'gps': (40.1632626, 44.2935926)}, {'name': 'Location 3', 'gps': (29.476705, 121.869339)}]
=========================================================
 The second_one way to print: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'}]
=========================================================
 The second_two way to print: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'}]
=========================================================
 The second_three way to print:pprint.pprint(p)
<__main__.Person object at 0x0000020EDCC52C10>
=========================================================
 The thrnd way to print:pp(p)
instance(Person):
  age: 10

参考文章

  1. 再见print
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章