How to Pretty Print to a String Not to a Shell in Python?

4.5/5 - (2 votes)

Understanding the pprint() Function in Python

You may know the pprint module and its pprint() function to pretty print a string, dictionary, set, or list.

If not, feel free to watch the following video and read the associated tutorial on the Finxter blog:

Python pprint - A Simple Guide to Pretty Printing

👉 Recommended Tutorial: Python pprint – A Simple Guide to Pretty Printing

Here’s an example where we don’t use pretty-printing on a dictionary—looks ugly, doesn’t it?

my_dict = {'alice': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           'bob': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           'carl': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           'dave': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
print(my_dict)

The output crams it all into a single line with forced line breaks:

You can pretty print it by importing the pprint module and call pprint():

import pprint

my_dict = {'alice': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           'bob': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           'carl': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           'dave': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
pprint.pprint(my_dict)

Much prettier output with one dictionary row per line:

But what if you want to take this output as a string instead of printing it to the shell? In other words: 👇

How to Pretty Print to a String Not Printing to Output Shell?

To pretty-print to a string instead of the standard output (std), use the pprint.pformat() function instead of pprint.pprint(). For example, to pretty-print a dictionary d to a string, use the expression pprint.pformat(d) and assign it to a string variable for further processing.

Here’s an example that makes this crystal clear:

import pprint


my_dict = {'alice': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           'bob': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           'carl': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           'dave': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}

my_string = pprint.pformat(my_dict)

print(type(my_string))
# <class 'str'>

print(my_string)

The output shows that the dictionary is now pretty-printed to a string variable instead of to the shell:

You can now do follow-up processing of the pretty-printed data structure such as storing it in a file, sending it over the web (programmatically), or analyzing it in your script.

💡 Note: You can pretty-print dictionaries, lists, sets, and tuples to strings the exact same way by using the pprint.pformat(x) function instead of pprint.pprint(x) for data structure x.