Explanation of python3 Code Output Nested Object Instance

  • 2021-08-12 03:08:05
  • OfStack

We all know that if you want your computer to run more programs, you have to increase its configuration to drive it. In the previous study, we have known something about function printing print, but the printing function of more complex objects, such as nested print, is not enough.

Some small partners are already looking for other functions. In fact, aiming at this problem, we can solve it by using a more advanced pprint. Next, we use code to output nested objects for simulation.

The default print function of Python can satisfy daily output tasks, but if you want to print larger, nested objects, the content printed with the default print function will be ugly.

This is when we need pprint, which allows complex structured objects to be displayed in a more readable format. This is an essential tool for Python developers who often have to face non-ordinary data structures.

The easiest way to use the pprint module is to call the pprint () method:


from pprint import pprint

from pprint_data import data

print('PRINT:')
print(data)
print()
print('PPRINT:')
pprint(data)

pprint (object, stream=None, indent=1, width=80, depth=None) formats the object and writes it to stream passed in as a parameter (sys. stdout by default).


PRINT:
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}), (2, {'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H', 'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L'}), (3, ['m', 'n']), (4, ['o', 'p', 'q']), (5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]
PPRINT:
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
 (2,
 {'e': 'E',
 'f': 'F',
 'g': 'G',
 'h': 'H',
 'i': 'I',
 'j': 'J',
 'k': 'K',
 'l': 'L'}),
 (3, ['m', 'n']),
 (4, ['o', 'p', 'q']),
 (5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]

Compared with print, print is more comprehensive in function, and can handle larger or nested objects. It is only necessary to repeat p at the beginning of print in memory.


Related articles: