Python中print和pprint两者的区别

概述

在python中,我们经常使用内置打印函数print来打印输出一些内容。然而打印出来的python数据结构对象总是以一行的形式展示,这样对数据结构复杂或数据较多的对象的显示并不美观,这时我们就可以使用python的另一个内置函数pprint来美化输出数据结构对象。

示例

我们以一个数据结构较为复杂的对象为例,从https://pypi.org/pypi/sampleproject/json获取这个数据结构对象,并分别使用print和pprint来查看两者的区别。

代码如下

import json
from pprint import pprint
from urllib.request import urlopen

with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
    project_info = json.load(resp)['info']

print(project_info)
pprint(project_info)

print函数打印的内容如下

{'author': 'A. Random Developer', 'author_email': 'author@example.com', 'bugtrack_url': None, 'classifiers': ['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Software Development :: Build Tools'], 'description': '# A sample Python project\n\n![Python Logo](https://www.python.org/static/community_logos/python-logo.png "Sample inline image")\n\nA sample project that exists as an aid to the [Python Packaging User\nGuide][packaging guide]\'s [Tutorial on Packaging and Distributing\nProjects][distribution tutorial].\n\nThis project does not aim to cover best practices for Python project\ndevelopment as a whole. For example, it does not provide guidance or tool\nrecommendations for version control, documentation, or testing.\n\n[The source for this project is available here][src].\n\nMost of the configuration for a Python project is done in the `setup.py` file,\nan example of which is included in this project. You should edit this file\naccordingly to adapt this sample project to your needs.\n\n----\n\nThis is the README file for the project.\n\nThe file should use UTF-8 encoding and can be written using\n[reStructuredText][rst] or [markdown][md use] with the appropriate [key set][md\nuse]. It will be used to generate the project webpage on PyPI and will be\ndisplayed as the project homepage on common code-hosting services, and should be\nwritten for that purpose.\n\nTypical contents for this file would include an overview of the project, basic\nusage examples, etc. Generally, including the project changelog in here is not a\ngood idea, although a simple “What\'s New” section for the most recent version\nmay be appropriate.\n\n[packaging guide]: https://packaging.python.org\n[distribution tutorial]: https://packaging.python.org/tutorials/packaging-projects/\n[src]: https://github.com/pypa/sampleproject\n[rst]: http://docutils.sourceforge.net/rst.html\n[md]: https://tools.ietf.org/html/rfc7764#section-3.5 "CommonMark variant"\n[md use]: https://packaging.python.org/specifications/core-metadata/#description-content-type-optional\n\n\n', 'description_content_type': 'text/markdown', 'docs_url': None, 'download_url': '', 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1}, 'home_page': 'https://github.com/pypa/sampleproject', 'keywords': 'sample setuptools development', 'license': '', 'maintainer': '', 'maintainer_email': '', 'name': 'sampleproject', 'package_url': 'https://pypi.org/project/sampleproject/', 'platform': '', 'project_url': 'https://pypi.org/project/sampleproject/', 'project_urls': {'Bug Reports': 'https://github.com/pypa/sampleproject/issues', 'Funding': 'https://donate.pypi.org', 'Homepage': 'https://github.com/pypa/sampleproject', 'Say Thanks!': 'http://saythanks.io/to/example', 'Source': 'https://github.com/pypa/sampleproject/'}, 'release_url': 'https://pypi.org/project/sampleproject/2.0.0/', 'requires_dist': ['peppercorn', "check-manifest ; extra == 'dev'", "coverage ; extra == 'test'"], 'requires_python': '>=3.5, <4', 'summary': 'A sample Python project', 'version': '2.0.0', 'yanked': False, 'yanked_reason': None}

pprint函数打印的内容如下

{'author': 'A. Random Developer',
 'author_email': 'author@example.com',
 'bugtrack_url': None,
 'classifiers': ['Development Status :: 3 - Alpha',
                 'Intended Audience :: Developers',
                 'License :: OSI Approved :: MIT License',
                 'Programming Language :: Python :: 3',
                 'Programming Language :: Python :: 3 :: Only',
                 'Programming Language :: Python :: 3.5',
                 'Programming Language :: Python :: 3.6',
                 'Programming Language :: Python :: 3.7',
                 'Programming Language :: Python :: 3.8',
                 'Topic :: Software Development :: Build Tools'],
 'description': '# A sample Python project\n'
                '\n'
                '![Python '
                'Logo](https://www.python.org/static/community_logos/python-logo.png '
                '"Sample inline image")\n'
                '\n'
                'A sample project that exists as an aid to the [Python '
                'Packaging User\n'
                "Guide][packaging guide]'s [Tutorial on Packaging and "
                'Distributing\n'
                'Projects][distribution tutorial].\n'
                '\n'
                'This project does not aim to cover best practices for Python '
                'project\n'
                'development as a whole. For example, it does not provide '
                'guidance or tool\n'
                'recommendations for version control, documentation, or '
                'testing.\n'
                '\n'
                '[The source for this project is available here][src].\n'
                '\n'
                'Most of the configuration for a Python project is done in the '
                '`setup.py` file,\n'
                'an example of which is included in this project. You should '
                'edit this file\n'
                'accordingly to adapt this sample project to your needs.\n'
                '\n'
                '----\n'
                '\n'
                'This is the README file for the project.\n'
                '\n'
                'The file should use UTF-8 encoding and can be written using\n'
                '[reStructuredText][rst] or [markdown][md use] with the '
                'appropriate [key set][md\n'
                'use]. It will be used to generate the project webpage on PyPI '
                'and will be\n'
                'displayed as the project homepage on common code-hosting '
                'services, and should be\n'
                'written for that purpose.\n'
                '\n'
                'Typical contents for this file would include an overview of '
                'the project, basic\n'
                'usage examples, etc. Generally, including the project '
                'changelog in here is not a\n'
                "good idea, although a simple “What's New” section for the "
                'most recent version\n'
                'may be appropriate.\n'
                '\n'
                '[packaging guide]: https://packaging.python.org\n'
                '[distribution tutorial]: '
                'https://packaging.python.org/tutorials/packaging-projects/\n'
                '[src]: https://github.com/pypa/sampleproject\n'
                '[rst]: http://docutils.sourceforge.net/rst.html\n'
                '[md]: https://tools.ietf.org/html/rfc7764#section-3.5 '
                '"CommonMark variant"\n'
                '[md use]: '
                'https://packaging.python.org/specifications/core-metadata/#description-content-type-optional\n'
                '\n'
                '\n',
 'description_content_type': 'text/markdown',
 'docs_url': None,
 'download_url': '',
 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': '',
 'maintainer': '',
 'maintainer_email': '',
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': '',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': {'Bug Reports': 'https://github.com/pypa/sampleproject/issues',
                  'Funding': 'https://donate.pypi.org',
                  'Homepage': 'https://github.com/pypa/sampleproject',
                  'Say Thanks!': 'http://saythanks.io/to/example',
                  'Source': 'https://github.com/pypa/sampleproject/'},
 'release_url': 'https://pypi.org/project/sampleproject/2.0.0/',
 'requires_dist': ['peppercorn',
                   "check-manifest ; extra == 'dev'",
                   "coverage ; extra == 'test'"],
 'requires_python': '>=3.5, <4',
 'summary': 'A sample Python project',
 'version': '2.0.0',
 'yanked': False,
 'yanked_reason': None}

由以上例子可以看出,对于特别长的数据打印,print输出结果都在一行,不方便查看,而pprint采用分行打印输出,打印出来的数据结构更加完整,更加方便阅读打印输出的结果。

总结

一般情况下,对于数据结构简单的数据,我们都用print来打印输出,而数据结构比较复杂、数据长度较长的数据,如果想通过美化展示输出的内容来提升数据阅读性,就需要使用pprint函数打印了。

posted @ 2021-04-22 10:53  蓝莓薄荷  阅读(511)  评论(0编辑  收藏  举报