Text Wrapping

When the output of our program is text-like, instead of tabular, it will usually be necessary to wrap it so that it can be displayed conveniently. Consider the following output, which overflows its line, and which uses a complicated print statement:

>>> saying = ['After', 'all', 'is', 'said', 'and', 'done', ',', ... 'more', 'is', 'said', 'than', 'done', '.']

After (5), all (3), is (2), said (4), and (3), done (4), , (1), more (4), is (2), said (4),

We can take care of line wrapping with the help of Python's textwrap module. For maximum clarity we will separate each step onto its own line:

>>> from textwrap import fill >>> format = '%s (%d),'

>>> pieces = [format % (word, len(word)) for word in saying] >>> output = ' '.join(pieces) >>> wrapped = fill(output) >>> print wrapped

After (5), all (3), is (2), said (4), and (3), done (4), , (1), more (4), is (2), said (4), than (4), done (4), . (1),

Notice that there is a linebreak between more and its following number. If we wanted to avoid this, we could redefine the formatting string so that it contained no spaces (e.g., '%s_(%d),'), then instead of printing the value of wrapped, we could print wrap ped.replace('_', ' ').

Was this article helpful?

0 0

Post a comment