Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is the difference between print and Pprint in Python?

The purpose is very simple, it is for printing anything in python. pprint() function also has similar functionality. But the only difference is in the way it prints complex data structures. The normal print() function prints the entire content in a single line.

How do I use Pprint in Python?

To use pprint, begin by importing the library at the top of your Python file. From here you can either use the . pprint() method or instantiate your own pprint object with PrettyPrinter() .

How do you format a string in Python?

To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.


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

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


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

Are you looking for pprint.pformat?


Something like this:

import pprint, StringIO

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