less than 1 minute read

The textwrap module can be used to format text for output in situations where pretty-printing is desired. It offers programmatic functionality similar to the paragraph wrapping or filling features found in many text editors and word processors.

Given a sample text:

sample_text = '''
    The textwrap module can be used to format text for output in
    situations where pretty-printing is desired.  It offers
    programmatic functionality similar to the paragraph wrapping
    or filling features found in many text editors.
    '''

you can clean up the text and then fill or wrap it using:

import textwrap

dedented_text = textwrap.dedent(sample_text).strip()

width = 45
print('{} Columns:\n'.format(width))
print(textwrap.fill(dedented_text, width=width))
print()

to get:


'''The textwrap module can be used to format
text for output in situations where pretty-
printing is desired.  It offers programmatic
functionality similar to the paragraph
wrapping or filling features found in many
text editors.'''

Via The Python 3 Module of the Week and enki.com.

Leave a comment