2020-05-24 python pprint方法

废话不多说,直接上代码

import pprint
test = {
"name":"zhangsan",
"age":18,
"gender":1,
"desc":{
    "addr":"beijing",
    "job":"IT"
}
}
pprint.pprint(test)
print(test) 

输出结果:

{'age': 18,
 'desc': {'addr': 'beijing', 'job': 'IT'},
 'gender': 1,
 'name': 'zhangsan'}
{'name': 'zhangsan', 'age': 18, 'gender': 1, 'desc': {'addr': 'beijing', 'job': 'IT'}}

pprint在打印内容较长较复杂的对象时,能以格式化的形式输出。

也可以自定义输出格式

import pprint
test = {
"name":"zhangsan",
"age":18,
"gender":1,
"desc":{
    "addr":"beijing",
    "job":"IT"
}
}

# 指定缩进和宽度
pp = pprint.PrettyPrinter(indent=4, width=20)
pp.pprint(test)

输出结果:

{   'age': 18,
    'desc': {   'addr': 'beijing',
                'job': 'IT'},
    'gender': 1,
    'name': 'zhangsan'}

 

但pprint不支持像print一样用“,”分隔就可以输出多个值

a = 1
b = 2
print(a,b) 
pprint.pprint("%s %s"%(a,b)) 
pprint.pprint(a,b)

输出结果;

1 2
'1 2'
Traceback (most recent call last):
  File "c:\xl.c\Code\pycharm\test.py", line 27, in <module>
    pprint.pprint(a,b)
  File "C:\xl.c\app\pythonInterpreter\python3\lib\pprint.py", line 53, in pprint
    printer.pprint(object)
  File "C:\xl.c\app\pythonInterpreter\python3\lib\pprint.py", line 148, in pprint
    self._format(object, self._stream, 0, 0, {}, 0)
  File "C:\xl.c\app\pythonInterpreter\python3\lib\pprint.py", line 185, in _format
    stream.write(rep)
AttributeError: 'int' object has no attribute 'write'

  

 

a = 1
b = 2
print(a,b)
pprint.pprint("%s %s"%(a,b))
pprint.pprint(a,b)
posted @ 2020-05-24 21:31  陈雪莲  阅读(247)  评论(0编辑  收藏  举报

welcome to myblog