python - 如何让 python 的 pprint 返回一个字符串而不是打印?

标签 python pretty-print pprint

换句话说,什么是 sprintf 等价于 pprint?

最佳答案

pprint模块有一个名为 pformat 的函数,就是为了这个目的。

来自文档:

Return the formatted representation of object as a string. indent, width and depth will be passed to the PrettyPrinter constructor as formatting parameters.

例子:

>>> 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'}]"

关于python - 如何让 python 的 pprint 返回一个字符串而不是打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/521532/

相关文章:

json - 如何使用 Play Framework 响应打印精美的 JSON 对象?

Python PrettyPrint 输出到变量

python - 我不明白 python 中 pprint 中的宽度字段

python - Pygame screen.blit() 来自非零 y 坐标

python - Numpy:如何有效地获取每行的topN个元素?

python - keras LSTM 预测不佳

java - 为什么 JSON pretty-print 不起作用?

python - 短时傅里叶变换和逆变换数据丢失: Need Help Improving Audio Quality

r - pretty-print 数据框时如何增加列之间的空间?

namespaces - 无法让 pprint 在 clojure 中工作