换句话说,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]}"
>>>
推荐文章
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?