drue
drue

Reputation: 5093

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

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

Upvotes: 280

Views: 112742

Answers (5)

Andrew Jaffe
Andrew Jaffe

Reputation: 27087

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

Upvotes: 21

SilentGhost
SilentGhost

Reputation: 319601

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

Upvotes: 395

russian_spy
russian_spy

Reputation: 6655

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

Upvotes: 19

Hans Nowak
Hans Nowak

Reputation: 7897

Something like this:

import pprint, StringIO

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

Upvotes: 14

sykloid
sykloid

Reputation: 101206

Are you looking for pprint.pformat?

Upvotes: 17

Related Questions