让Python更漂亮的显示数据

2.1 更漂亮的显示数据

2.1.1 漂亮的显示非常长的数据

使用pprint模块中的pprint函数可以自动将要打印的内容进行调整,使得输出的内容比较方便查看。

from pprint import pprint
data = {
    
    x: chr(x) for x in range(65,91)}
print(data)
pprint(data)

print效果:
{65: ‘A’, 66: ‘B’, 67: ‘C’, 68: ‘D’, 69: ‘E’, 70: ‘F’, 71: ‘G’, 72: ‘H’, 73: ‘I’, 74: ‘J’, 75: ‘K’, 76: ‘L’, 77: ‘M’, 78: ‘N’, 79: ‘O’, 80: ‘P’, 81: ‘Q’, 82: ‘R’, 83: ‘S’, 84: ‘T’, 85: ‘U’, 86: ‘V’, 87: ‘W’, 88: ‘X’, 89: ‘Y’, 90: ‘Z’}
pprint效果:
{65: ‘A’,
66: ‘B’,
67: ‘C’,
68: ‘D’,
69: ‘E’,
70: ‘F’,
71: ‘G’,
72: ‘H’,
73: ‘I’,
74: ‘J’,
75: ‘K’,
76: ‘L’,
77: ‘M’,
78: ‘N’,
79: ‘O’,
80: ‘P’,
81: ‘Q’,
82: ‘R’,
83: ‘S’,
84: ‘T’,
85: ‘U’,
86: ‘V’,
87: ‘W’,
88: ‘X’,
89: ‘Y’,
90: ‘Z’}

2.1.2 漂亮的显示JSON数据

有时候JSON数据比较大并且堆积在一起,或者排版不是很好,显示出来层次效果不满足效果,这个时候可以通过json库中dumps方法进行输出,主要是设置indent参数,如下:

from pprint import pprint
import json
data_json='{"$schema":"http://json-schema.org/draft-06/schema#","$id":"https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#","description":"Meta-schemafor$datareference(JSON-schemaextensionproposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}'
print('未处理的显示效果:')
print(data_json)
data_python = json.loads(data_json)
print('处理后的显示效果:')
print(json.dumps(data_python, indent=2))

未处理的显示效果:
{“KaTeX parse error: Expected 'EOF', got '#' at position 48: …draft-06/schema#̲","id”:“https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/KaTeX parse error: Expected 'EOF', got '#' at position 10: data.json#̲","description"…datareference(JSON-schemaextensionproposal)”,“type”:“object”,“required”:[“KaTeX parse error: Expected '}', got 'EOF' at end of input: …"properties":{"data”:{“type”:“string”,“anyOf”:[{“format”:“relative-json-pointer”},{“format”:“json-pointer”}]}},“additionalProperties”:false}
处理后的显示效果:
{
KaTeX parse error: Expected 'EOF', got '#' at position 49: …draft-06/schema#̲", "id”: “https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/KaTeX parse error: Expected 'EOF', got '#' at position 10: data.json#̲", "descript…datareference(JSON-schemaextensionproposal)”,
“type”: “object”,
“required”: [
KaTeX parse error: Expected '}', got 'EOF' at end of input: …ties": { "data”: {
“type”: “string”,
“anyOf”: [
{
“format”: “relative-json-pointer”
},
{
“format”: “json-pointer”
}
]
}
},
“additionalProperties”: false
}

猜你喜欢

转载自blog.csdn.net/crleep/article/details/130223324