不曾见过的Python函数——pprint.pprint()

本文介绍了Python中的pprint模块,该模块提供了一种美观打印数据结构的方法。通过使用pprint,可以将复杂的数据结构以易于阅读的形式展示出来。文章中通过示例展示了如何使用pprint来格式化不同类型的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pprint模块提供了打印出任何Python数据结构类和方法。
pprint 包含一个“美观打印机”,用于生成数据结构的一个美观视图。格式化工具会生成数据结构的一些表示,不仅可以由解释器正确地解析,而且便于人类阅读。输出尽可能放在一行上,分解为多行时则需要缩进。

>>>import pprint

>>>data = (
    "this is a string", [1, 2, 3, 4], ("more tuples",
    1.0, 2.3, 4.5), "this is yet another string"
    )

>>>pprint.pprint(data)

('this is a string',
[1, 2, 3, 4],
('more tuples', 1.0, 2.3, 4.5),
'this is yet another string')
### 如何使用 `pprint` 模块处理 `Response.json()` 的数据 在 Python 中,`pprint` 是一个用于美化打印复杂结构(如字典、列表等)的标准库模块。相比于普通的 `print` 函数,`pprint` 提供更清晰的输出格式,尤其适合调试和查看嵌套的数据结构。 以下是关于如何结合 `requests.Response.json()` 和 `pprint` 使用的具体说明: #### 1. 安装依赖并导入必要模块 为了获取网络请求的结果并解析 JSON 数据,通常会用到 `requests` 库。如果尚未安装该库,则可以通过以下命令安装: ```bash pip install requests ``` 接着,在脚本中导入必要的模块: ```python import requests from pprint import pprint ``` #### 2. 发起 HTTP 请求并提取 JSON 数据 通过 `requests.get()` 方法发起 GET 请求,并调用 `.json()` 将响应体转换为 Python 字典对象。例如: ```python url = 'https://example-api.com/data' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' } response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() else: print(f"Error: Unable to fetch data. Status code: {response.status_code}") ``` 此处假设 API 返回的是一个包含评论 (`comments`) 的 JSON 对象[^1]。 #### 3. 使用 `pprint` 美化打印数据 一旦成功获取了 JSON 数据,可以利用 `pprint` 来展示其内容。对于特定字段(如 `comments`),可以直接访问对应的键值对并传递给 `pprint` 函数: ```python for comment in data.get('comments', []): # 遍历 comments 列表 pprint(comment) # 输出单条评论的内容 ``` 此方法不仅适用于简单的键值对,还能够优雅地呈现复杂的嵌套结构[^1]。 #### 4. 示例代码综合演示 下面是一个完整的例子,展示了如何从远程服务器抓取数据并通过 `pprint` 展现结果: ```python import requests from pprint import pprint def fetch_and_print_comments(api_url): try: headers = {'User-Agent': 'Custom User Agent'} res = requests.get(api_url, headers=headers) if res.status_code != 200: raise Exception(f"Failed with status {res.status_code}") json_data = res.json() # Assuming the key is named 'comments' and it's a list of dictionaries. for idx, item in enumerate(json_data.get('comments', [])[:5]): # Print first five items only print(f"\nComment #{idx + 1}:") pprint(item) except Exception as e: print(f"An error occurred: {e}") # Example usage api_endpoint = "https://mocked-comments-endpoint/api/v1" fetch_and_print_comments(api_endpoint) ``` 以上程序定义了一个函数来封装逻辑流程,便于重复调用或扩展功能[^1]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值