当前位置:首页 > Python > 正文

Python pprint.pformat()函数使用教程 - 格式化输出复杂数据结构

Python pprint.pformat() 函数使用教程

学习如何使用pprint.pformat()格式化输出复杂数据结构,提升代码可读性和调试效率

pprint.pformat() 简介

pprint.pformat() 是 Python 标准库中 pprint 模块提供的一个函数,用于生成数据结构的"漂亮打印"字符串表示形式。

pprint.pprint() 直接打印格式化结果不同,pprint.pformat() 返回格式化后的字符串,让你可以存储、处理或进一步操作格式化输出。

基本语法

import pprint

formatted_str = pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)

参数说明

  • object:要格式化的Python对象
  • indent:缩进空格数(默认为1)
  • width:一行最大宽度(默认为80)
  • depth:控制打印的层级深度
  • compact:是否使用紧凑模式(默认为False)
  • sort_dicts:是否对字典键排序(默认为True)

基本使用示例

📝 示例代码
import pprint

data = {
    'name': 'John Doe',
    'age': 30,
    'address': {
        'street': '123 Main St',
        'city': 'Anytown',
        'zip': '12345'
    },
    'scores': [95, 87, 92, 78, 88],
    'contacts': [
        {'type': 'email', 'value': 'john@example.com'},
        {'type': 'phone', 'value': '555-1234'}
    ]
}

formatted = pprint.pformat(data, indent=2, width=60)
print(formatted)
🖥️ 输出结果
{ 'address': { 'city': 'Anytown',
              'street': '123 Main St',
              'zip': '12345'},
  'age': 30,
  'contacts': [ {'type': 'email', 'value': 'john@example.com'},
                {'type': 'phone', 'value': '555-1234'}],
  'name': 'John Doe',
  'scores': [95, 87, 92, 78, 88]}

与标准 print()str() 相比,pprint.pformat() 的输出更易读,尤其是处理嵌套数据结构时。

与普通打印对比

普通 print() 输出
{'name': 'John Doe', 'age': 30, 'address': {'street': '123 Main St', 'city': 'Anytown', 'zip': '12345'}, 'scores': [95, 87, 92, 78, 88], 'contacts': [{'type': 'email', 'value': 'john@example.com'}, {'type': 'phone', 'value': '555-1234'}]}
pprint.pformat() 输出
{ 'address': { 'city': 'Anytown',
              'street': '123 Main St',
              'zip': '12345'},
  'age': 30,
  'contacts': [ {'type': 'email', 'value': 'john@example.com'},
                {'type': 'phone', 'value': '555-1234'}],
  'name': 'John Doe',
  'scores': [95, 87, 92, 78, 88]}

普通打印将所有内容放在一行,难以阅读,而 pprint.pformat() 格式化的输出结构化清晰,层次分明。

高级参数使用

控制缩进 (indent)

# 使用4空格缩进
formatted = pprint.pformat(data, indent=4)

控制行宽 (width)

# 设置行宽为40个字符
formatted = pprint.pformat(data, width=40)

控制深度 (depth)

# 只显示2层深度
formatted = pprint.pformat(data, depth=2)

紧凑模式 (compact)

# 使用紧凑模式
formatted = pprint.pformat(data, compact=True)

字典键排序 (sort_dicts)

# 不对字典键排序
formatted = pprint.pformat(data, sort_dicts=False)

实际应用场景

📝 日志记录

格式化复杂数据结构以便在日志文件中清晰记录,提高日志可读性。

🐞 调试输出

调试时输出复杂对象,便于快速定位数据结构中的问题。

💾 数据存储

将格式化后的数据结构存储到文件中,便于后续人工查看。

📊 数据展示

在Web应用或命令行工具中展示格式化数据,提升用户体验。

文件存储示例

import pprint
import json

# 将格式化数据写入文件
with open('formatted_data.txt', 'w') as f:
    f.write(pprint.pformat(data, indent=2))
    
# 与json.dumps()对比
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)

使用技巧与最佳实践

  • 对于特别大的数据结构,设置depth参数避免输出过多内容
  • 调试时使用sort_dicts=False保持字典原始顺序
  • 在日志记录中结合pprint.pformat()和日志级别控制输出
  • 为不同场景调整width参数(终端 vs 文件)
  • 处理自定义对象时,确保它们有良好的__repr__方法

性能考虑

对于非常大的数据结构,pprint.pformat() 可能比普通 str() 转换更耗时。在性能敏感场景中应谨慎使用。

本教程介绍了Python pprint.pformat()函数的使用方法和最佳实践

发表评论