In other words, what's the sprintf equivalent for pprint
?
How do I get Python's pprint to return a string instead of printing?
Asked Answered
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'}]"
sort_dicts
was implemented in python 3.8 –
Norseman 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()
>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>
Something like this:
import pprint, StringIO
s = StringIO.StringIO()
pprint.pprint(some_object, s)
print s.getvalue() # displays the string
technically the only "correct" answer considering only the title –
Toby
© 2022 - 2024 — McMap. All rights reserved.
sort_dicts=False
to the arguments ofpprint.pformat
, because this preserves the original order of dictionaries. (I think this option is only valid with the newer versions of Python). – Pteridology