如何获取python的pprint返回字符串而不是打印?


180

换句话说,什么是sprintf等同于pprint?

Answers:


262

pprint模块有一个名为命令pformat,只是这个目的。

从文档中:

以字符串形式返回对象的格式化表示形式。缩进,宽度和深度将作为格式参数传递给PrettyPrinter构造函数。

例:

>>> import pprint
>>> people = [
...     {"first": "Brian", "last": "Kernighan"}, 
...     {"first": "Dennis", "last": "Richie"},
... ]
>>> pprint.pformat(people, indent=4)
"[   {   'first': 'Brian', 'last': 'Kernighan'},\n    {   'first': 'Dennis', 'last': 'Richie'}]"


14
>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>


8

像这样:

import pprint, StringIO

s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string 

1
从技术上讲,仅考虑标题的唯一“正确”答案
villasv
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.