Python Textwrap Module
The textwrap module provides some convenience functions, as well as TextWrapper, the class that does all the work. If youβre just wrapping or filling one or two text strings, the convenience functions should be good enough; otherwise, you should use an instance of TextWrapper for efficiency.
Importing the Module
import textwrap
Wrapping Text
textwrap.wrap()
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.
import textwrap
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.
'''
# Dedent first to remove common leading whitespace
dedented_text = textwrap.dedent(sample_text).strip()
print(textwrap.wrap(dedented_text, width=50))
textwrap.fill()
Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for "\n".join(wrap(text, ...)).
import textwrap
print(textwrap.fill(dedented_text, width=50))
Indenting and Dedenting
textwrap.dedent()
Remove any common leading whitespace from every line in text. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.
import textwrap
s = '''\
Hello
World
'''
print(repr(s)) # Output: ' Hello\n World\n '
print(repr(textwrap.dedent(s))) # Output: 'Hello\n World\n'
textwrap.indent()
Add prefix to the beginning of selected lines in text.
import textwrap
s = 'hello\n\n \nworld'
print(textwrap.indent(s, '+ '))
# Output:
# + hello
# +
# +
# + world
Shortening Text
textwrap.shorten()
Collapse and truncate the given text to fit in the given width.
import textwrap
text = "Hello world, this is a long text."
print(textwrap.shorten(text, width=20))
# Output: Hello world, [...]
You can customize the placeholder.
print(textwrap.shorten(text, width=20, placeholder="..."))
# Output: Hello world, this...