Skip to content

Python pprint module method | Example code

  • by

Python pprint() Method formatted and more readable way console output. You will get it in a neat, and presentable fashion compares to using the print() function.

Syntax of pprint method

pprint.pprint(object, stream=None, indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True)
  • indent: The amount of indent when there are multiple lines
  • width: The amount of width between two data objects
  • depth: The number of levels which need to be printed
  • stream: An output stream (where the data is displayed) can be set-up
  • compact: It helps fit as many objects as possible within every line’s width

Python pprint method example

Simple example code print data objects in a pretty format, more readable, and well-formatted (pprint itself means pretty print).

The pprint module provides a capability to “pretty-print” arbitrarily, you have to import this module.

import pprint

my_dict = {1: 'a', 2: 'b', 3: 'z', 4: 'm', "Code": 'Python'}

pprint.pprint(my_dict, indent=1, width=40, depth=5)

Output:

Python pprint module method

Another example

Get data from API and show output using pprint() method. Response is in a JSON format.

import json
import requests
from pprint import pprint

res = requests.get("https://reqres.in/api/products/3")
data = json.loads(res.text)

# printing json response
pprint(data)

Do comment if you have any doubts or suggestions so this Python print topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *