Sil*_*ost 239
该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'}]"
Run Code Online (Sandbox Code Playgroud)
rus*_*spy 13
>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>
Run Code Online (Sandbox Code Playgroud)
像这样的东西:
import pprint, StringIO
s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52264 次 |
| 最近记录: |