- publishing free software manuals
An Introduction to Python
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 124 pages
ISBN 0954161769
RRP £12.95 ($19.95)

Sales of this book support the Python Software Foundation! Get a printed copy>>>

11.1 Output Formatting

The ‘repr’ module provides a version of repr() customized for abbreviated displays of large or deeply nested containers:

    >>> import repr   
    >>> repr.repr(set('supercalifragilisticexpialidocious'))
    "set(['a', 'c', 'd', 'e', 'f', 'g', ...])"

The ‘pprint’ module offers more sophisticated control over printing both built-in and user defined objects in a way that is readable by the interpreter. When the result is longer than one line, the "pretty printer" adds line breaks and indentation to more clearly reveal data structure:

    >>> import pprint
    >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']],
     [['magenta', 'yellow'], 'blue']]]
    >>> pprint.pprint(t, width=30)
    [[[['black', 'cyan'],
       'white',
       ['green', 'red']],
      [['magenta', 'yellow'],
       'blue']]]

The ‘textwrap’ module formats paragraphs of text to fit a given screen width:

    >>> import textwrap
    >>> doc = """The wrap() method is just like
    ... fill() except that it returns a list of
    ... strings instead of one big string with
    ... newlines to separate the wrapped
    ... lines."""
    ...
    >>> print textwrap.fill(doc, width=40)
    The wrap() method is just like fill()
    except that it returns a list of strings
    instead of one big string with newlines
    to separate the wrapped lines.

The ‘locale’ module accesses a database of culture specific data formats. The grouping attribute of locale's format function provides a direct way of formatting numbers with group separators:

    >>> import locale
    >>> locale.setlocale(locale.LC_ALL,
                         'English_United States.1252')
    'English_United States.1252'
    >>> conv = locale.localeconv()  # get map of conventions
    >>> x = 1234567.8
    >>> locale.format("%d", x, grouping=True)
    '1,234,567'
    >>> locale.format("%s%.*f", (conv['currency_symbol'],
    ...	      conv['frac_digits'], x), grouping=True)
    '$1,234,567.80'
ISBN 0954161769An Introduction to PythonSee the print edition