mirror of
https://github.com/apachecn/ailearning.git
synced 2026-02-11 06:15:22 +08:00
57 lines
847 B
Markdown
57 lines
847 B
Markdown
# pprint 模块:打印 Python 对象
|
||
|
||
`pprint` 是 pretty printer 的缩写,用来打印 Python 数据结构,与 `print` 相比,它打印出来的结构更加整齐,便于阅读。
|
||
|
||
In [1]:
|
||
|
||
```py
|
||
import pprint
|
||
|
||
```
|
||
|
||
生成一个 Python 对象:
|
||
|
||
In [2]:
|
||
|
||
```py
|
||
data = (
|
||
"this is a string",
|
||
[1, 2, 3, 4],
|
||
("more tuples", 1.0, 2.3, 4.5),
|
||
"this is yet another string"
|
||
)
|
||
|
||
```
|
||
|
||
使用普通的 `print` 函数:
|
||
|
||
In [3]:
|
||
|
||
```py
|
||
print data
|
||
|
||
```
|
||
|
||
```py
|
||
('this is a string', [1, 2, 3, 4], ('more tuples', 1.0, 2.3, 4.5), 'this is yet another string')
|
||
|
||
```
|
||
|
||
使用 `pprint` 模块中的 `pprint` 函数:
|
||
|
||
In [4]:
|
||
|
||
```py
|
||
pprint.pprint(data)
|
||
|
||
```
|
||
|
||
```py
|
||
('this is a string',
|
||
[1, 2, 3, 4],
|
||
('more tuples', 1.0, 2.3, 4.5),
|
||
'this is yet another string')
|
||
|
||
```
|
||
|
||
可以看到,这样打印出来的公式更加美观。 |