C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Fill: This method does the same thing as textwrap.wrap except it returns the data joined into a single, newline-separated string.