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

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


Solution 1:

The pprint module has a command 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'}]"

Solution 2:

Assuming you really do mean pprint from the pretty-print library, then you want the pprint.pformat method.

If you just mean print, then you want str()