文章内容

2025/9/16 19:16:34,作 者: 黄兵

Python print 如何格式化输出

最近再调试 Python 程序的时候,需要格式化输出,具体代码如下:

d = {'area_code': None, 'balance_after': 0.0, 'cost': 5.0, 'end_time': 'Thu, 16 Oct 2025 07:37:48 GMT', 'phone_number': '9559640863', 'start_time': 'Tue, 16 Sep 2025 07:37:48 GMT', 'status': 'success'}

如果我们需要格式化输出 d,应该怎么写呢?

可以用 pprint 或者 json.dumps 来格式化输出,让字典看起来更美观、易读。

下面是具体代码:

from pprint import pprint

d = {
    'area_code': None,
    'balance_after': 0.0,
    'cost': 5.0,
    'end_time': 'Thu, 16 Oct 2025 07:37:48 GMT',
    'phone_number': '9559640863',
    'start_time': 'Tue, 16 Sep 2025 07:37:48 GMT',
    'status': 'success'
}

pprint(d)

结果会自动对齐、换行,输出更易读。

还有一种方法是:用 json.dumps(适合日志或调试)

import json

print(json.dumps(d, indent=4, ensure_ascii=False))

indent=4 会让输出缩进 4 个空格,ensure_ascii=False 可以保证中文正常显示。
输出示例:

{
    "area_code": null,
    "balance_after": 0.0,
    "cost": 5.0,
    "end_time": "Thu, 16 Oct 2025 07:37:48 GMT",
    "phone_number": "9559640863",
    "start_time": "Tue, 16 Sep 2025 07:37:48 GMT",
    "status": "success"
}

这样就完成了格式化输出。

分享到:

发表评论

评论列表