A tutorial on formatting output using the Pprint function in Python _python

Source: Internet
Author: User
Tags data structures print print pprint

pprint– Beautiful Print

Function: Beautiful print data structure

Pprint contains an "aesthetically pleasing printer" for generating a beautiful view of the data structure. The formatting tool generates some representations of the data structure that can be parsed correctly by the interpreter and is easy for humans to read. The output is placed on one line as much as possible, and indentation is required when decomposed into multiple rows.

The following example contains data in the use of

data = [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 '

      },

    ]

1, printing

The easiest way to use this module is to use the Pprint () function

From pprint import pprint
print print: '
print data
print 
print ' pprint: '
pprint (data)

Run Result:

PRINT:
[1, {' A ': ' A ', ' C ': ' C ', ' B ': ' B ', ' d ': ' d '}), (2, {' E ': ' E ', ' g ': ' G ', ' F ': ' f ', ' I ': ' l ', ' H ': ' H ', ' K ': ' K ') , ' J ': ' J ', ' l ': ' l '}]
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 '
  }]

Pprint () Formats an object and writes it to a data stream, which is passed as a parameter (or is the default sys.stdout)

Note Why a vertical column is displayed in the second dictionary because pprint print supports vertical column printing above 8 objects

2. Format

To format a data structure without writing it directly to a stream (for example, for logging), you can use Pformat () to construct a string representation.

Import logging from
pprint import pformat
logging.basicconfig (level = logging. DEBUG,
          format = '% (levelname) -8s% (message) s ',
          )
logging.debug (' Logging pformatted data ')
formatted = Pformat (data) for line in
Formatted.splitlines ():
  logging.debug (Line.rstrip ())

Run Result:

Debug  Logging pformatted data
Debug  [(1, {' A ': ' A ', ' B ': ' B ', ' C ': ' C ', ' d ': ' d '}),
debug   (2,
Debug   {' E ': ' E ',
debug    ' F ': ' F ', Debug '    G ': ' G ',
debug    ' h ': ' H    ', Debug ' I ': ' I ',
debug    ' J ': ' J ',
debug    ' K ': ' K ',
debug    ' l ': ' l '}]

You can then print a formatted string or log it individually

Splitlines () split by Row ()

Rstrip () Remove the space on the right Lstrip () remove the left space strip () to remove both sides of the space. The default is to remove spaces, or you can pass in characters that need to be removed from either side or side, such as strip (' a '), which is to remove the character ' a ' on either side of the string
3, any class

If a custom class defines a __repr__ () method, the Prettyprinter class used by Pprint () can also handle these custom classes.

From Pprint import Pprint 
class Node (object):
  def __init__ (self,name,contents =[]):
    self.name = name
    Self.contents = contents[:]
  def __repr__ (self): return
    (' node (' + repr (self.name) + ', ' +
        repr ( self.contents) + ') '
trees = [Node (' node-1 '),
     node (' node-2 ', [Node (' node-2-1 ')]),
     node (' node-3 ' , [Node (' Node-3-1 ')]),     
     ]
pprint (trees)

Run Result:

[Node (' node-1 ', []],
 node (' node-2 ', [Node (' node-2-1 ', [])]),
 node (' node-3 ', [Node (' Node-3-1 ', [])]]

A representation of a nested object combined by Prettyprinter to return a full string representation.
4, Recursive

The recursive data structure is represented by a reference to the original data source, in the form of <recursion on TypeName with Id=number>.

From pprint import pprint 
local_data = [' A ', ' B ', 1,2]
local_data.append (local_data)
print ' ID (local_data) => ', id (local_data)
pprint (local_data)
print Local_data

Run Result:

ID (local_data) => 47458332363520
[' A ', ' B ', 1, 2, <recursion on List with id=47458332363520>]
[' A ', ' B ', 1, 2, [...]]

In this example, the list Local_data is added to itself, which creates a recursive reference

The built-in function ID () is to get the ID value of the object, in theory, each object has an ID value, if it is an integer and a string ((relatively small), then the same value will have the same ID value, but if the class, the same time will have different ID values. The test is as follows:

#int or float or Lon are the same (relatively small)
a = 65464131311513l
B = 65464131311513l
c = 65464131311513l
print ID (a) 
   print ID (b) Print
ID (c)
print
a = ' 12312312 '
b = ' 12312312 '
c = ' 12312312 '
print ID (a) Print
ID (b) Print
ID (c)
print 
a = 65464131311513l*11
B = 65464131311513l*11
c = 65464131311513L*11 Print ID (a) Print ID (
b) Print
ID (c)
print
a = ' 12312312 ' *11
b = ' 12312312 ' *11
c = ' 12312312 ' *11 print ID (a) Print ID (b) Print ID (
c)
Print 
class Test ( Object:
  def __init__ (self): pass
a = Test ()
B = Test ()
c = Test ()
print ID (a)
Print ID (b) Print
ID (c)
print

Test results:

47010342174992

47010342174992

47010342174992


47010343272096

47010343272096

47010343272096


47010343261568

47010343261648

47010343261688


47010343200944

47010343199152

47010343202352


47010343252304

47010343252944

47010343253008

5. Restrict nested output

For very deep data structures, the output may not be required to contain all the details. It is possible that the data is not locally formatted and may be formatted too large to be managed, or unnecessary to write down data.

From pprint import pprint 
print ' depth 1: '
pprint (data,depth=1)
print 
print ' depth 2: '
pprint ( data,depth=2)
print 
print ' depth 3: '
pprint (data,depth=3)

Run Result:

Depth 1:
[(...), (...)]
Depth 2:
[(1, {...}], (2, {...})]
Depth 3:
[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 '}]


   

Use the depth parameter to control the depth of the nested data structure recursively processed by the pleasing printer. Levels not included in the output are represented by an ellipsis
6. Control output Width

The default output width of formatted text is 80 columns. To adjust this width, you can use the parameter width in Pprint ().

From Pprint import pprint
for width in [80,5]:
  print ' width = ', Width
  pprint (data,width = width)
  prin T

Run Result:

WIDTH =
[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 '}]
WIDTH = 5
[(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 '}]

If the width size does not fit into the formatted data structure, if the cut or change is introduced into the illegal syntax, there will be no truncation or career change.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.