1.

What does pprint() function do? Is it the same as print() function?

Answer»

Whereas print() is a built-in FUNCTION that displays value of one or more arguments on the output console, pprint() function is defined in the pprint built-in module. The name stands for pretty print. The pprint() function PRODUCES an aesthetically good looking output of Python DATA structures. Any data structure that is properly parsed by the Python interpreter is ELEGANTLY formatted. It tries to keep the formatted EXPRESSION in one line as far as possible, but generates into multiple lines if the length exceeds the width parameter of formatting. 

In order to use it, first it must be imported from pprint module.

from pprint import pprint

One of the unique features of pprint output is that it automatically sorts dictionaries before the display representation is formatted. 

>>> from pprint import pprint >>> ctg={'Electronics':['TV', 'Washing machine', 'Mixer'], 'computer':{'Mouse':200, 'Keyboard':150,'Router':1200},'stationery':('Book','pen', 'notebook')} >>> pprint(ctg) {'Electronics': ['TV', 'Washing machine', 'Mixer'],  'computer': {'Keyboard': 150, 'Mouse': 200, 'Router': 1200},  'stationery': ('Book', 'pen', 'notebook')}

The pprint module also has definition of PrettyPrinter class, and pprint() method belongs to it. 

>>> from pprint import PrettyPrinter >>> pp=PrettyPrinter() >>> pp.pprint(ctg) {'Electronics': ['TV', 'Washing machine', 'Mixer'],  'computer': {'Keyboard': 150, 'Mouse': 200, 'Router': 1200},  'stationery': ('Book', 'pen', 'notebook')}


Discussion

No Comment Found