In Python code, the textwrap
module provides wrapping for plain text. This can improve text files that are inconsistently wrapped.
In many text files, some lines are longer than others. With Python code, we can count characters and rewrap these lines.
We must first include textwrap
through an import statement at the top. Here we use a triple-quoted string
to store some text.
for
-statement. We can manipulate or join the list.import textwrap value = """The image in these opening lines evidently refers to a bird knocking itself out, in full flight, against the outer surface of a glass pane in which a mirrored sky, with its slightly darker tint and slightly slower cloud, presents the illusion of continued space.""" # Wrap this text. list = textwrap.wrap(value, width=50) # Print each line. for element in list: print(element)The image in these opening lines evidently refers to a bird knocking itself out, in full flight, against the outer surface of a glass pane in which a mirrored sky, with its slightly darker tint and slightly slower cloud, presents the illusion of continued space.
Other methods, such as fill()
are helpful. This method does the same thing as textwrap.wrap
except it returns the data joined into a single, newline-separated string
.
With textwrap
, we access effective text wrapping methods. With this helpful module we can often avoid writing our own line-breaking algorithms.