In other words, what's the sprintf equivalent to pprint?
Asked
Active
Viewed 9.6k times
5 Answers
372
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'}]"

charlie
- 389
- 3
- 16

SilentGhost
- 307,395
- 66
- 306
- 293
-
3Thanks 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). – C-3PO Jun 02 '21 at 13:52
-
`sort_dicts` was implemented in python 3.8 – Gruber May 04 '22 at 13:39
21
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()

charlie
- 389
- 3
- 16

Andrew Jaffe
- 26,554
- 4
- 50
- 59
19
>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>

russian_spy
- 6,465
- 4
- 30
- 26
15
Something like this:
import pprint, StringIO
s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string

Hans Nowak
- 7,600
- 1
- 18
- 18