换句话说,sprintf相当于pprint?
pprint模块有一个名为pformat的函数,正是为了这个目的。
从文档中可以看到:
返回object的格式化表示形式为字符串。缩进, width和depth将作为参数传递给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'}]"
就像这样:
import pprint, StringIO
s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string
>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>