Purpose of the module : Format paragraph text by adjusting the position of paragraph breaks in each line of text.
textwrap
Modules can be used to format text in some scenarios that require beautiful output (printing) of text. It provides programmatic features like paragraph wrapping, padding, etc. used in many text editors and word processors.
sample data
For the examples in this section we create textwrap_example.py
modules that contain a multi-line string sample_text
.
# textwrap_example.py
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.
'''
Fill paragraph (Fill)
fill()
The method takes text as input and returns the formatted text.
# textwrap_fill.py
import textwrap
from textwrap_example import sample_text
print(textwrap.fill(sample_text, width=50))
The results were not satisfactory. The text is now left-aligned, but the first line of text retains its leading indentation, and the leading whitespace of the remaining lines is embedded in the middle of the paragraph.
$ python3 textwrap_fill.py
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.
Dedent
In the previous example, our formatted text output was mixed with some tabs and extra whitespace, so it didn't look pretty. method to remove common whitespacededent()
at the beginning of each line of text in the sample string , which can make the result look nicer. The sample string is artificially added whitespace to illustrate this feature.
# textwrap_dedent.py
import textwrap
from textwrap_example import sample_text
dedented_text = textwrap.dedent(sample_text)
print('Dedented:')
print(dedented_text)
The results are starting to look pretty:
$ python3 textwrap_dedent.py
Dedented:
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.
dedent()
(remove indent) is the opposite of "indent" (indent/whitespace), the result of the method is that the common whitespacededent()
at the beginning of each line of text is removed. But if a line of text itself has more whitespace than other lines, the extra whitespace will not be removed.
For example, to replace blank spaces with underscores _
, enter:
_Line one.
__Line two.
_Line Three.
Then the output is:
Line one.
_Line two.
Line Three.
Combining Dedent and Fill
Next, the text after stripping the leading whitespace can be passed to the fill()
method and width
tested with different parameter values:
# textwrap_fill_width.py
import textwrap
from textwrap_example import sample_text
dedented_text = textwrap.dedent(sample_text).strip()
for width in [45, 60]:
print('{} Columns: \n'.format(width))
print(textwrap.fill(dedented_text, width=width))
print()
The result is as follows:
$ python3 textwrap_fill_width.py
45 Columns:
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.
60 Columns:
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.
Add indented text
Use indent()
method to add consistent prefix text at the beginning of each line of a multiline string. The following example adds a >
prefix to the beginning of each line of a sample string, making it the format quoted in an email reply.
# textwrap_indent.py
import textwrap
from textwrap_example import sample_text
dedented_text = textwrap.dedent(sample_text)
wrapped = textwrap.fill(dedented_text, width=50)
wrapped += '\n\nSecond paragraph after a blank line.'
final = textwrap.indent(wrapped, '> ')
print('Quoted block:\n')
print(final)
The sample paragraph is split into each new line, prefixing each line, and the lines are >
then combined into a new string and returned.
$ python3 textwrap_indent.py
Quoted block:
> 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.
> Second paragraph after a blank line.
If we want to control which lines are prefixed, we can indent()
pass predicate
an assertion parameter to the method, which is a method. For each line of text, the indent()
method first calls the method to judge, and if the method returns True
, add a prefix in front of this line, Otherwise it is not added.
# textwrap_indent_predicate.py
import textwrap
from textwrap_example import sample_text
def should_indent(line):
print('Indent {!r}?'.format(line))
return len(line.strip()) % 2 == 0
dedented_text = textwrap.dedent(sample_text)
wrapped = textwrap.fill(dedented_text, width=50)
final = textwrap.indent(wrapped, 'EVEN ', predicate=should_indent)
print('\nQuoted block:\n')
print(final)
The result is that we only prefix each line with an even length:
$ python3 textwrap_indent_predicate.py
Indent ' The textwrap module can be used to format text\n'?
Indent 'for output in situations where pretty-printing is\n'?
Indent 'desired. It offers programmatic functionality\n'?
Indent 'similar to the paragraph wrapping or filling\n'?
Indent 'features found in many text editors.'?
Quoted block:
EVEN The textwrap module can be used to format text
for output in situations where pretty-printing is
EVEN desired. It offers programmatic functionality
EVEN similar to the paragraph wrapping or filling
EVEN features found in many text editors.
Convex row (paragraph indent)
We can also use fill()
methods to add prefixes. Similarly, we can set the width of the output, and the prefix text of the first line of text can be set separately.
# textwrap_hanging_indent.py
import textwrap
from textwrap_example import sample_text
dedented_text = textwrap.dedent(sample_text)
print(textwrap.fill(dedented_text, initial_indent='', subsequent_indent=' ' * 4, width=50))
This makes it easy to produce a "convex" text, where the first line of text is less indented than other lines.
$ python3 textwrap_hanging_indent.py
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.
Prefix text can also be non-whitespace characters, such as an asterisk, *
to produce a paragraph of bullet points.
Truncate long strings
We can use shorten()
methods to truncate longer strings to produce a summary or summary. All whitespace characters such as tabs, newlines, and strings of spaces are replaced with a single space . The text is truncated at less than or equal to the required text length, all at word boundaries to avoid incomplete words.
# textwrap_shorten.py
import textwrap
from textwrap_example import sample_text
dedented_text = textwrap.dedent(sample_text)
original = textwrap.fill(dedented_text, width=50)
print('Original:\n')
print(original)
shortened = textwrap.shorten(original, 100)
shortened_wrapped = textwrap.fill(shortened, width=50)
print('\nShortened:\n')
print(shortened_wrapped)
If non-whitespace characters in the original string are stripped, then it is replaced by a placeholder. The default placeholder is [...]
that it can be set by shorten()
passing a placeholder
parameter to the method.
$ python3 textwrap_shorten.py
Original:
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.
Shortened:
The textwrap module can be used to format text for
output in situations where pretty-printing [...]
Reference:
1. Official documentation of the textwrap module