Computer >> Computer tutorials >  >> Programming >> Python

Data pretty printer (pprint) in Python


Python has the ability to properly format the content of a print method using a special method called pretty print or pprint. For example when we read a content of an url which is in the form of json, the content will be printed as single line which is hard to read or comprehend. But if we apply pretty print, python gives it a ice structure as per the json tags.

Without pprint

In the below program we are printing the json content of a web page using the traditional print method. The entire result comes as a single line.

Example

import requests
json_url_link = "https://pypi.org/pypi/sampleproject/json"
result = requests.get(json_url_link )
print(result.json())

Output

Running the above code gives us the following result −

{'info': {'author': 'The Python Packaging Authority', 'author_email': '[email protected]', . . .

With pprint

Next we take the same content as above but apply the pprint now. As you can see the output format is very organized.

Example

import requests
from pprint import pprint
json_url_link = "https://pypi.org/pypi/sampleproject/json"
result = requests.get(json_url_link )
pprint(result.json())

Output

Running the above code gives us the following result −

{'info': {'author': 'The Python Packaging Authority',
         'author_email': '[email protected]',
         'bugtrack_url': None,
         'classifiers': ['Development Status :: 3 - Alpha',
                        'Intended Audience :: Developers',
                        'License :: OSI Approved :: MIT License',
                        'Programming Language :: Python :: 2',
                        'Programming Language :: Python :: 2.7',