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

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

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

In other words, what’s the sprintf equivalent to pprint?


回答 0

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'}]"

The pprint module has a command named pformat, for just that purpose.

From the documentation:

Return the formatted representation of object as a string. indent, width and depth will be passed to the PrettyPrinter constructor as formatting parameters.

Example:

>>> 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'}]"

回答 1

假设您确实pprintpretty-print库中获取了意思,那么您需要该pprint.pformat方法。

如果您只是想说 print,那么您想要str()

Assuming you really do mean pprint from the pretty-print library, then you want the pprint.pformat method.

If you just mean print, then you want str()


回答 2

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

回答 3

您在找pprint.pformat吗?

Are you looking for pprint.pformat?


回答 4

像这样:

import pprint, StringIO

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

Something like this:

import pprint, StringIO

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