ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 对比普通 print():
  • 使用场景
  • 注意事项
  • 总结

pprint 模块是 Python 中用于美化输出数据结构的标准库模块(全称 Pretty Printer),尤其适合打印嵌套复杂的数据(如多层嵌套的字典、列表)。与普通的 print() 相比,它能自动格式化输出,使其更易读。


### **核心功能:`pprint()` 函数**
#### 基本用法:
```python
from pprint import pprint

data = {
    "name": "Alice",
    "age": 30,
    "pets": [{"type": "dog", "name": "Buddy"}, {"type": "cat", "name": "Whiskers"}],
    "address": {"city": "Wonderland", "zipcode": "12345"}
}

pprint(data)

输出效果(自动缩进和换行):

{'address': {'city': 'Wonderland', 'zipcode': '12345'},
 'age': 30,
 'name': 'Alice',
 'pets': [{'name': 'Buddy', 'type': 'dog'},
          {'name': 'Whiskers', 'type': 'cat'}]}

对比普通 print(): #

print(data)  # 输出挤在一行,难以阅读
# {'name': 'Alice', 'age': 30, ... } (杂乱)

### **关键参数:定制输出格式**
`pprint()` 支持以下常用参数:
| 参数 | 作用 | 示例 |
|------|------|------|
| `indent` | 缩进空格数 | `pprint(data, indent=4)` |
| `width` | 每行最大字符数(默认 80) | `pprint(data, width=20)` |
| `depth` | 最大嵌套层级(超限显示 `...`) | `pprint(data, depth=1)` |
| `sort_dicts` | 是否对字典键排序(默认 `True`) | `pprint(data, sort_dicts=False)` |
| `compact` | 紧凑模式(默认 `False`) | `pprint(data, compact=True)` |

#### 示例:
```python
pprint(data, indent=2, width=30, depth=2)

输出(缩进 2 空格,宽度 30,只显示 2 层嵌套):

{ 'address': { ... },
  'age': 30,
  'name': 'Alice',
  'pets': [ ... ]}

### **其他实用功能**
1. **`pformat()` 函数**  
   返回美化后的字符串(不直接打印),用于日志/文件写入:
   ```python
   from pprint import pformat
   formatted_str = pformat(data)
   with open("output.txt", "w") as f:
       f.write(formatted_str)
  1. PrettyPrinter 类
    创建自定义的打印机对象(复用配置):
    from pprint import PrettyPrinter
    custom_printer = PrettyPrinter(indent=4, width=100)
    custom_printer.pprint(data)  # 使用自定义配置
    `

使用场景 #

  • 调试复杂数据结构:如 JSON 响应、配置字典。
  • 日志记录:使日志文件更易读。
  • 数据报告:输出结构化的分析结果。 `

注意事项 #

  1. 默认对字典键排序(字母序),可通过 sort_dicts=False 关闭。
  2. 长字符串不会自动换行(如长 URL),必要时手动处理。
  3. 对自定义对象无效(需实现 __repr__ 方法)。 `

总结 #

场景 推荐工具
快速美化打印 pprint()
获取美化字符串 pformat()
复用配置打印 PrettyPrinter 类

通过 pprint,你可以告别杂乱的数据输出,让调试和日志阅读变得高效!

访问验证

请输入访问令牌

Token不正确,请重新输入