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

dru*_*rue 159 python

换句话说,什么是sprintf相当于pprint?

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)

  • 感谢您的代码,它真的很有帮助。作为 2021 年的旁注,在许多情况下,将“sort_dicts=False”添加到“pprint.pformat”的参数中很有用,因为这保留了字典的原始顺序。(我认为这个选项仅对较新版本的Python有效)。 (3认同)

And*_*ffe 15

假设你真的是pprint漂亮的印刷库中做出意思,那么你想要这个pprint.pformat方法.

如果你只是意味着 print,那么你想要str()


rus*_*spy 13

>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>
Run Code Online (Sandbox Code Playgroud)


syk*_*ora 10

你在找pprint.pformat


Han*_*wak 6

像这样的东西:

import pprint, StringIO

s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string 
Run Code Online (Sandbox Code Playgroud)

  • 从技术上讲,仅考虑标题的唯一“正确”答案 (2认同)