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?
Answers:
Just use the StringIO
module:
import StringIO
output = StringIO.StringIO()
Now you may pass output
as a stream to prettyprint
.
You should simply call the pformat function from the pprint module:
import pprint
s = pprint.pformat(aDict)
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
}
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?
Just use the StringIO
module:
import StringIO
output = StringIO.StringIO()
Now you may pass output
as a stream to prettyprint
.
You should simply call the pformat function from the pprint module:
import pprint
s = pprint.pformat(aDict)
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
}