PrettyPrint python变成了一个字符串,而不是stdout

era*_*ran 31 python

我想使用prettyprint打印出一个字典,但是要用字符串而不是控制台.该字符串将传递给其他函数.

我知道我可以使用"stream"参数来指定文件而不是sys.out但我想要一个字符串.

我怎么做?

Sim*_*got 87

您只需从pprint模块调用pformat函数:

import pprint
s = pprint.pformat(aDict)
Run Code Online (Sandbox Code Playgroud)

  • 这需要设置为正确的答案,因为请求是pprint作为字符串,pformat是**方法.它由pprint模块提供了这个目的. (3认同)
  • 比通过`StringIO`,恕我直言更加pythonic (2认同)

roo*_*oot 9

我有时会使用json模块:

In [1]: import json

In [2]: d = {'a':1, 'b':2, 'c':{'a':1}}

In [3]: s = json.dumps(d, indent=4)

In [4]: s
Out[4]: '{\n    "a": 1, \n    "c": {\n        "a": 1\n    }, \n    "b": 2\n}'

In [5]: print s
{
    "a": 1, 
    "c": {
        "a": 1
    }, 
    "b": 2
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ker 0

只需使用该StringIO模块

import StringIO

output = StringIO.StringIO()
Run Code Online (Sandbox Code Playgroud)

现在您可以output作为流传递到prettyprint.