我想使用prettyprint打印出一个字典,但是要用字符串而不是控制台.该字符串将传递给其他函数.
我知道我可以使用"stream"参数来指定文件而不是sys.out但我想要一个字符串.
我怎么做?
Sim*_*got 87
您只需从pprint模块调用pformat函数:
import pprint
s = pprint.pformat(aDict)
Run Code Online (Sandbox Code Playgroud)
我有时会使用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)
只需使用该StringIO模块:
import StringIO
output = StringIO.StringIO()
Run Code Online (Sandbox Code Playgroud)
现在您可以output作为流传递到prettyprint.
| 归档时间: |
|
| 查看次数: |
11057 次 |
| 最近记录: |