How do I get python's pprint to return a string instead of printing?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping
--
Chapters
00:00 How Do I Get Python'S Pprint To Return A String Instead Of Printing?
00:12 Accepted Answer Score 389
00:38 Answer 2 Score 17
00:47 Answer 3 Score 20
01:03 Answer 4 Score 15
01:11 Thank you
--
Full question
https://stackoverflow.com/questions/5215...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #prettyprint #pprint
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping
--
Chapters
00:00 How Do I Get Python'S Pprint To Return A String Instead Of Printing?
00:12 Accepted Answer Score 389
00:38 Answer 2 Score 17
00:47 Answer 3 Score 20
01:03 Answer 4 Score 15
01:11 Thank you
--
Full question
https://stackoverflow.com/questions/5215...
--
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