textwrap
The textwrap module provides a set of utilities for formatting plain text paragraphs. It can wrap text to a specified line width, dedent multiline strings by removing common leading whitespace, shorten text while preserving word boundaries, and add consistent indentation. These functions are useful for generating human‑readable output, formatting docstrings, and preparing text for display in consoles or reports.
Syntax
import textwrap
The module is part of the Python standard library; no external dependencies are required.
Key Functions
wrap()
textwrap.wrap(text, width=70, **kwargs)
Wraps a single paragraph of text so every line is at most width characters long. Returns a list of lines.
| Parameter | Type | Default | Description |
|---|---|---|---|
text | str | — | The input paragraph to wrap. |
width | int | 70 | Maximum line length. |
expand_tabs | bool | True | Replace tabs with spaces before wrapping. |
replace_whitespace | bool | True | Replace each whitespace character with a single space. |
drop_whitespace | bool | True | Drop leading and trailing whitespace from each line. |
initial_indent | str | '' | String to prepend to the first line. |
subsequent_indent | str | '' | String to prepend to all lines after the first. |
max_lines | int | None | Maximum number of lines; extra content is replaced by placeholder. |
placeholder | str | ' [modules::]' | String appended when text is truncated. |
fill()
textwrap.fill(text, width=70, **kwargs)
A convenience function that wraps text and joins the resulting lines with newlines, returning a single string.
dedent()
textwrap.dedent(text)
Removes any common leading whitespace from every line in text. Useful for cleaning up triple‑quoted strings that are indented with the surrounding code.
shorten()
textwrap.shorten(text, width, placeholder=' [modules::]')
Truncates text to at most width characters, preserving whole words where possible, and appends placeholder. The returned string will never exceed width characters.
indent()
textwrap.indent(text, prefix)
Adds prefix to the beginning of every line in text. Empty lines are left unchanged.
TextWrapper class
For repeated wrapping with the same settings, create a TextWrapper instance. Its constructor accepts the same keyword arguments as wrap().
wrapper = textwrap.TextWrapper(width=40, subsequent_indent=' ')
Examples
Basic wrapping
import textwrap
paragraph = "The quick brown fox jumps over the lazy dog."
wrapped = textwrap.wrap(paragraph, width=20)
print(wrapped)
# ['The quick brown fox', 'jumps over the lazy', 'dog.']
filled = textwrap.fill(paragraph, width=20)
print(filled)
# The quick brown fox
# jumps over the lazy
# dog.
Dedenting a multiline string
code = '''
def hello():
print("Hello, world!")
'''
dedented = textwrap.dedent(code)
print(dedented)
# def hello():
# print("Hello, world!")
Shortening long text
long_text = "Python is an interpreted, high‑level, general‑purpose programming language."
short = textwrap.shorten(long_text, width=40)
print(short)
# Python is an interpreted, high‑level, [modules::]
Indenting a block
lines = "line1\nline2\nline3"
indented = textwrap.indent(lines, prefix='> ')
print(indented)
# > line1
# > line2
# > line3
Custom TextWrapper
wrapper = textwrap.TextWrapper(width=30, initial_indent='* ', subsequent_indent=' ')
result = wrapper.fill(paragraph)
print(result)
# * The quick brown fox jumps
# over the lazy dog.
Common Patterns
Formatting docstrings: Use dedent() to remove indentation when extracting docstrings from source code.
Console output formatting: Use fill() to wrap long error messages or help text to the terminal width.
Generating bullet lists: Combine indent() with wrap() to produce consistently indented bullet points.
Truncating previews: shorten() is ideal for generating summary snippets in UI displays.
Errors
The module raises no custom exceptions. However, if width is less than the length of any single word (after whitespace replacement), wrap() and fill may produce lines longer than width. The shorten() function may raise ValueError if width is smaller than the length of the placeholder.