Fix Python – How do I get python’s pprint to return a string instead of printing?

Question

Asked By – drue

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

Now we will see solution for issue: How do I get python’s pprint to return a string instead of printing?


Answer

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

This question is answered By – SilentGhost

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0