Answers for "pprint python example"

3

pprint python

# pprint (aka prettyprint) is a function that allow to print objects in a clearer way
# Fist you need to import the pprint module
import pprint
# then you can create a printer whith whatever arguments you need
my_printer = pprint.PrettyPrinter(width=20)
# default arguments are : indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True

# let's take this list as an exemple:
list1 = [[0,1,2,3,4],[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]]

print(list1) # will print [[0,1,2,3,4],[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]]
my_printer.pprint(list1) # will print:
# [[0, 1, 2, 3, 4],
#  [1, 2, 3, 4, 5],
#  [2, 3, 4, 5, 6],
#  [3, 4, 5, 6, 7]]

# You can also formant text whith pprint
output = my_printer.pformat(list1)
# output will be:
"""[[0, 1, 2, 3, 4],
 [1, 2, 3, 4, 5],
 [2, 3, 4, 5, 6],
 [3, 4, 5, 6, 7]]"""
Posted by: Guest on May-21-2021
4

python print dict pretty

>>> import json
>>> print json.dumps({'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}},
...                  sort_keys=True, indent=4)
{
    "a": 2,
    "b": {
        "x": 3,
        "y": {
            "t1": 4,
            "t2": 5
        }
    }
}
Posted by: Guest on November-25-2020
1

python pretty print

import pprint

student_dict = {'Name': 'Tusar', 'Class': 'XII', 
     'Address': {'FLAT ':1308, 'BLOCK ':'A', 'LANE ':2, 'CITY ': 'HYD'}}

print student_dict
print "n"
print "***With Pretty Print***"
print "-----------------------"
pprint.pprint(student_dict,width=-1)
Posted by: Guest on December-08-2020

Python Answers by Framework

Browse Popular Code Answers by Language