Search code examples
pythonwidthconceptpprint

I don't understand the width field in pprint in python


I don't understand this concept clearly. Could somebody give me some examples to demonstrate the concept for width in pprint in python?


Solution

  • Basically it tries to limit your output to a specific width.

    Here's an example:

    import pprint
    stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
    pp = pprint.PrettyPrinter(width=80)
    pp.pprint(stuff)
    

    result is:

    ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
    

    but if you do the same thing but change the width(say to 10):

    import pprint
    stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
    pp = pprint.PrettyPrinter(width=10)
    pp.pprint(stuff)
    

    you get:

    ['spam',
     'eggs',
     'lumberjack',
     'knights',
     'ni']
    

    This is a modified example from the python docs ( http://docs.python.org/library/pprint.html ). For things like this, I find it easier to just open the python interrupter and play around and see how the commands react to what you enter.