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

时间:2013-02-26 09:09:16

标签: python

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

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

我该怎么做?

3 个答案:

答案 0 :(得分:82)

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

import pprint
s = pprint.pformat(aDict)

答案 1 :(得分:8)

我有时会使用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
}

答案 2 :(得分:1)

只需使用StringIO module

import StringIO

output = StringIO.StringIO()

现在,您可以将output作为信息流传递给prettyprint