Is there a pretty printer for python data?

蓝咒 提交于 2019-12-03 23:01:17
from pprint import pprint
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
pprint(a)

Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.

Somtimes YAML can be good for this.

import yaml
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
print yaml.dump(a)

Produces:

- 0
- 1
- [a, b, c]
- 2
- 3
- 4

In addition to pprint.pprint, pprint.pformat is really useful for making readable __repr__s. My complex __repr__s usually look like so:

def __repr__(self):
    from pprint import pformat

    return "<ClassName %s>" % pformat({"attrs":self.attrs,
                                       "that_i":self.that_i,
                                       "care_about":self.care_about})

Another good option is to use IPython, which is an interactive environment with a lot of extra features, including automatic pretty printing, tab-completion of methods, easy shell access, and a lot more. It's also very easy to install.

IPython tutorial

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!