How do I get Python's pprint to return a string instead of printing?
Asked Answered
F

5

273

In other words, what's the sprintf equivalent for pprint?

Furrier answered 6/2, 2009 at 18:25 Comment(0)
K
384

The pprint module has a function named pformat, for just that purpose.

From the documentation:

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

Example:

>>> 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'}]"
Koester answered 6/2, 2009 at 18:28 Comment(2)
Thanks for the code, it was really helpful. As a sidenote for 2021, in many contexts it is useful to add sort_dicts=False to the arguments of pprint.pformat, because this preserves the original order of dictionaries. (I think this option is only valid with the newer versions of Python).Pteridology
sort_dicts was implemented in python 3.8Norseman
D
20

Assuming you really do mean pprint from the pretty-print library, then you want the pprint.pformat function.

If you just mean print, then you want str()

Dinin answered 6/2, 2009 at 18:29 Comment(0)
B
19
>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>
Bakker answered 24/6, 2011 at 19:30 Comment(0)
B
17

Are you looking for pprint.pformat?

Brazil answered 6/2, 2009 at 18:29 Comment(0)
C
15

Something like this:

import pprint, StringIO

s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string 
Collaborative answered 6/2, 2009 at 18:30 Comment(1)
technically the only "correct" answer considering only the titleToby

© 2022 - 2024 — McMap. All rights reserved.