PrettyPrint python into a string, and not stdout

Question:

I’d like to use prettyprint to print out a dictionary, but into a string and not to console.
This string is to be passed on to other functions.

I know I can use the “stream” parameter to specify a file instead of sys.out but I want a string.

How do I do that?

Asked By: eran

||

Answers:

Just use the StringIO module:

import StringIO

output = StringIO.StringIO()

Now you may pass output as a stream to prettyprint.

Answered By: David Zwicker

You should simply call the pformat function from the pprint module:

import pprint
s = pprint.pformat(aDict)
Answered By: Simon Bergot

I sometimes use the json module for that:

In [1]: import json

In [2]: d = {'a':1, 'b':2, 'c':{'a':1}}

In [3]: s = json.dumps(d, indent=4)

In [4]: s
Out[4]: '{n    "a": 1, n    "c": {n        "a": 1n    }, n    "b": 2n}'

In [5]: print s
{
    "a": 1, 
    "c": {
        "a": 1
    }, 
    "b": 2
}
Answered By: root
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.