HomeSearch

Python Textwrap Wrap Example

Use the textwrap module and the wrap method. Wrap text to a certain number of characters.
Textwrap. The textwrap module provides wrapping for plain text. Often text files are inconsistently wrapped. Some lines are longer than others. With code, we can count characters and rewrap lines.
Example. Using the textwrap module is simple. We must first include textwrap through an import statement at the top. Here we use a triple-quoted string to store a sentence of text. We then invoke the textwrap.wrap method.

Width: We specify the optional argument width to the wrap method. By default, width is 70, but we want something a bit narrower.

List: The wrap method returns a list. We can loop over this list with a for-statement. We can manipulate or join the list.

Output: In the output, we see the wrapped text. The longest line in it, the third line, is exactly 50 characters long.

So: Textwrap.wrap here correctly wrapped the sample text, which is from a book by Vladimir Nabokov.

Python program that uses textwrap.wrap 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) Output 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. The textwrap module is simple to use. This is part of its appeal. If it were complex to use, writing your own text wrapping method might be more convenient. Other methods, such as fill() are helpful.Textwrap: Python.org

Fill: This method does the same thing as textwrap.wrap except it returns the data joined into a single, newline-separated string.

Summary. Python comes with many helpful modules included. With textwrap, we access effective text wrapping methods. This prevents repetitive coding tasks: we can often avoid writing our own line-breaking algorithms.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls