Home
Python
textwrap Example (wrap)
Updated Jan 17, 2024
Dot Net Perls
Textwrap. In Python code, the textwrap module provides wrapping for plain text. This can improve text files that are inconsistently wrapped.
Wrapping issues. In many text files, some lines are longer than others. With Python code, we can count characters and rewrap these lines.
Example. We must first include textwrap through an import statement at the top. Here we use a triple-quoted string to store some text.
Note We specify the optional argument width to the wrap method. By default, width is 70, but we want something a bit narrower.
Return The wrap method returns a list. We can loop over this list with a for-statement. We can manipulate or join the list.
String List
Finally In the output, we see the wrapped text. The longest line in it, the third line, is exactly 50 characters long.
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.
Discussion. 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.
Summary. With textwrap, we access effective text wrapping methods. With this helpful module we can often avoid writing our own line-breaking algorithms.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 17, 2024 (grammar).
Home
Changes
© 2007-2025 Sam Allen