Home > python > catch the output of pprint in a string

catch the output of pprint in a string

Problem
If you have a large nested data structure (e.g. a list or dictionary), the pprint module is very useful to nicely format the output.

However, “pprint.pprint” prints directly to the stdout. What if you want to store the nicely formatted output in a string?

Solution
Use “pprint.pformat” instead.

Example:

>>> import pprint
>>> d = {"one": 1, "two": 2}
>>> pprint.pprint(d)
{'one': 1, 'two': 2}
>>> s = pprint.pformat(d)
>>> s
"{'one': 1, 'two': 2}"

Well, this is a small example, the real pretty formatting is not visible, but you get the point :)

Categories: python Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: