Pprint in Python

  • 2020-04-02 14:32:00
  • OfStack

1. The background

See mentioned pprint (link: http://bbs.csdn.net/topics/390335772).  
I'm going to give it a try.

2. Pprint profile

Find the online website to explain:

(link: http://docs.python.org/2/library/pprint.html#module-pprint http://

It's just a nice thing for you to print out some relatively complex variables.

3. Use pprint

Try writing some code.


Code:


#-------------------------------------------------------------------------------
# Name:        [record] toss and turn Python In the pprint
# Author:      Crifan Li
#
# Created:     06/01/2013
# Copyright:   (c) Crifan Li 2013
#------------------------------------------------------------------------------- import pprint;
import re; def pprintDemo():
    varsList = [
        [1, 2, 3],
        ["ab", "c", "def"],
        re.compile("w+"),
        ("123", "abc"),
        {
            "key1":"value1",
            "key2":"value2",
        },
    ];     for value in varsList:
        print value;     print "-"*80;     pp = pprint.PrettyPrinter(indent=4);
    for value in varsList:
        pp.pprint(value);     print "="*80;
    stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'];
    stuff.insert(0, stuff[:]);
    print stuff;
    print "-"*80;
    pp.pprint(stuff) if __name__ == '__main__':
    pprintDemo();

Effect:


[1, 2, 3]
['ab', 'c', 'def']
<_sre.SRE_Pattern object at 0x00000000030DD378>
('123', 'abc')
{'key2': 'value2', 'key1': 'value1'}
--------------------------------------------------------------------------------
[1, 2, 3]
['ab', 'c', 'def']
<_sre.SRE_Pattern object at 0x00000000030DD378>
('123', 'abc')
{   'key1': 'value1', 'key2': 'value2'}
================================================================================
[['spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', 'knights', 'ni']
--------------------------------------------------------------------------------
[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']

4. To summarize

Pprint, that's interesting.

You can use it later in code debugging.


Related articles: