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

PythonPretty PrintPprint

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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 - Python

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

Solution 3 - Python

Are you looking for pprint.pformat?

Solution 4 - Python

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

Solution 5 - Python

Something like this:

import pprint, StringIO

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondrueView Question on Stackoverflow
Solution 1 - PythonSilentGhostView Answer on Stackoverflow
Solution 2 - PythonAndrew JaffeView Answer on Stackoverflow
Solution 3 - PythonsykoraView Answer on Stackoverflow
Solution 4 - Pythonrussian_spyView Answer on Stackoverflow
Solution 5 - PythonHans NowakView Answer on Stackoverflow