17

How to store a Python PrettyPrint output to some variable.

Any other way than eyeD3?

like this -

string_output = pp.pprint(dict)
4

1 回答 1

26

使用pprint.pformat功能:

>>> my_dict = dict((i, i) for i in range(30))
>>> pp.pformat(my_dict)
'{0: 0,\n 1: 1,\n 2: 2,\n 3: 3,\n 4: 4,\n 5: 5,\n 6: 6,\n 7: 7,\n 8: 8,\n 9: 9,\n 10: 10,\n 11: 11,\n 12: 12,\n 13: 13,\n 14: 14,\n 15: 15,\n 16: 16,\n 17: 17,\n 18: 18,\n 19: 19,\n 20: 20,\n 21: 21,\n 22: 22,\n 23: 23,\n 24: 24,\n 25: 25,\n 26: 26,\n 27: 27,\n 28: 28,\n 29: 29}'
>>> print(pp.pformat(my_dict))
{0: 0,
 1: 1,
 2: 2,
 3: 3,
 4: 4,
 5: 5,
 6: 6,
 7: 7,
 8: 8,
 9: 9,
 10: 10,
 11: 11,
 12: 12,
 13: 13,
 14: 14,
 15: 15,
 16: 16,
 17: 17,
 18: 18,
 19: 19,
 20: 20,
 21: 21,
 22: 22,
 23: 23,
 24: 24,
 25: 25,
 26: 26,
 27: 27,
 28: 28,
 29: 29}
于 2013-07-04T06:47:53.337 回答