The Python Oracle

How do I get python's pprint to return a string instead of printing?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Question
00:20 Accepted answer (Score 360)
00:59 Answer 2 (Score 20)
01:17 Answer 3 (Score 19)
01:28 Answer 4 (Score 17)
01:40 Thank you

--

Full question
https://stackoverflow.com/questions/5215...

Accepted answer links:
[pprint]: http://docs.python.org/library/pprint.ht...
[pformat]: http://docs.python.org/library/pprint.ht...

Answer 2 links:
[pretty-print library]: http://docs.python.org/library/pprint.ht...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #prettyprint #pprint

#avk47



ACCEPTED ANSWER

Score 389


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



ANSWER 2

Score 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()




ANSWER 3

Score 17


Are you looking for pprint.pformat?




ANSWER 4

Score 15


Something like this:

import pprint, StringIO

s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string