pprint模块(美化输出)

pprint: python内置模块,主要提供一些函数,用于替代print()函数,美化一些python内置的数据类型的输出,比如dict, tuple, list, dataclass等等。

pprint.pp(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=False, underscore_numbers=False): 是我们主要使用的函数,通过一些参数来设置输出效果。

stream: 默认值是None,代表输出到控制台,与print()函数的默认输出位置一样,是sys.stdout。 而我们可以传递一个file-like object,比如文件对象,函数会自动调用文件的write()方法将内容输出到文件中。
indent: 用来控制嵌套结构的缩进长度。
width: 用来控制一行的长度,超过这个长度就换行。但如果长度设置的过小,比如一个列表中每个元素字符个数都超过了5个,而还将width设置为5的话,一行仍然会输出至少一个元素。
depth: 控制输出嵌套的层级,超过这个层级时,会用...来省略。 默认值为None,代表不限定层级。
compact: 控制是否紧凑输出内容,但是在width控制的一行长度限度内尽量紧凑。默认值为False,代表尽量换行。
sort_dicts: 控制输出典时是否按key来排序。 默认是False,即不排序。
underscore_numbers: 控制输出整数时,是否使用"_"来当做千分位符显示。

下面演示一下indent的效果

import pprint

data = {"name": "Alice", "age": 25, "hobbies": {"key1": 'reading', 'key2': "cycling"}}

pprint.pp(data, width=30)
print('-' * 25, '分隔线', '-' * 25)
pprint.pp(data, width=30, indent=5)

输出结果:

{'name': 'Alice',
 'age': 25,
 'hobbies': {'key1': 'reading',
             'key2': 'cycling'}}
------------------------- 分隔线 -------------------------
{    'name': 'Alice',
     'age': 25,
     'hobbies': {    'key1': 'reading',
                     'key2': 'cycling'}}

可以看出,indent的缩进效果并不好。

下面示例演示了width和compact参数的效果。

import pprint

data = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]

pprint.pp(data, compact=True)
print('-' * 25, '分隔线', '-' * 25)
pprint.pp(data, compact=False)
print('-' * 25, '分隔线', '-' * 25)
pprint.pp(data, width=30, compact=True)
print('-' * 25, '分隔线', '-' * 25)
pprint.pp(data, width=30, compact=False)

输出结果:

['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']
------------------------- 分隔线 -------------------------
['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']
------------------------- 分隔线 -------------------------
['apple', 'banana', 'cherry',
 'date', 'elderberry', 'fig',
 'grape']
------------------------- 分隔线 -------------------------
['apple',
 'banana',
 'cherry',
 'date',
 'elderberry',
 'fig',
 'grape']

从输出结果上看,compact是受到width影响的。
下面示例演示depth参数的效果。

import pprint

data = {"name": "Alice", "age": 25, "hobbies": ["reading", "cycling"], 
        'others': {'key1': 'value1', 
                   'nested': {'nested_key1': 'nested_value1', 'nested_key2': 'nested_value2'} ,
                   'key2': 'value2'
                   }
        }

pprint.pp(data)
print('-' * 25, '分隔线', '-' * 25)
pprint.pp(data, depth=2)

输出结果:

{'name': 'Alice',
 'age': 25,
 'hobbies': ['reading', 'cycling'],
 'others': {'key1': 'value1',
            'nested': {'nested_key1': 'nested_value1',
                       'nested_key2': 'nested_value2'},
            'key2': 'value2'}}
------------------------- 分隔线 -------------------------
{'name': 'Alice',
 'age': 25,
 'hobbies': ['reading', 'cycling'],
 'others': {'key1': 'value1', 'nested': {...}, 'key2': 'value2'}}

注意到,当depth=2时,只显示了两层内容,字典嵌套的第三层用{...}的形式省略掉了。
下面演示一下sort_dicts参数效果。

import pprint

data = {"name": "Alice", "age": 25, 'money': 999999999}

pprint.pp(data)
print('-' * 25, '分隔线', '-' * 25)
pprint.pp(data, sort_dicts=True)

输出结果:

{'name': 'Alice', 'age': 25, 'money': 999999999}
------------------------- 分隔线 -------------------------
{'age': 25, 'money': 999999999, 'name': 'Alice'}

下面演示underscore_numbers参数作用。

import pprint

data = {"name": "Alice", "age": 25, 'money': 999999999}

pprint.pp(data)
print('-' * 25, '分隔线', '-' * 25)
pprint.pp(data, underscore_numbers=True)

输出结果:

{'name': 'Alice', 'age': 25, 'money': 999999999}
------------------------- 分隔线 -------------------------
{'name': 'Alice', 'age': 25, 'money': 999_999_999}

pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False): 函数使用方法与pp()几乎一样,除了它的sort_dicts参数的默认值为True,即输出字典时默认会对key重新排序。

pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False): 相当于调用了pprint函数,但并不输出,而是将格式化的结果返回,我们可以用变量接收它,然后打印或者写入文件。

import pprint

data = {"name": "Alice", "age": 25, 'money': 999999999}

pprint.pp(data)

print('-' * 25, '分隔线', '-' * 25)
v = pprint.pformat(data, underscore_numbers=True)
print(v)

输出结果:

{'name': 'Alice', 'age': 25, 'money': 999999999}
------------------------- 分隔线 -------------------------
{'age': 25, 'money': 999_999_999, 'name': 'Alice'}

由于pformat的参数缺省值与pprint一致,即sort_dicts默认为True,所以输出字典时会按key重新排序。

class pprint.PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True, underscore_numbers=False): 可以用PrettyPrinter类实例化一个对象,然后再调用PrettyPrinter.pformat(object)和PrettyPrinter.pprint(object)方法来达到前面单独用pprint(), pformat()函数相同的效果,但一般不会这样用。

输出长文本字符串: 当pp函数输出的不是list,dict等类型,而只是一个字符串时,它会在长度合适,遇到'\n'的时候换行。如果很长的字符串并且没有换行符,它会按照width来截成多行,但也会找合适的位置,比如单词与单词之间的空格。
并且输出结果是字面量,可以直接复制粘贴到代码中的。

import pprint
import string

pprint.pp(string.ascii_letters+'\n'+string.ascii_letters+'\n'+string.ascii_letters)

print('-' * 25, '分隔线', '-' * 25)

s = "This is a long string that contains multiple sentences. It should be formatted properly by pprint to make it more readable."
pprint.pp(s)

输出结果:

('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n'
 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n'
 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
------------------------- 分隔线 -------------------------
('This is a long string that contains multiple sentences. It should be '
 'formatted properly by pprint to make it more readable.')
posted @ 2025-02-18 20:24  RolandHe  阅读(462)  评论(0)    收藏  举报