Text Wrapping & Formatting (textwrap)
Published by Brayan K
The textwrap module reflows plain text to a chosen line width and tidies indentation, turning a long run-on string into neat, readable lines.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Wrapping returns lines; filling joins them into one string
textwrap formats plain text paragraphs for a chosen character width. It is useful for command-line help, generated notices and readable reports. Start by deciding whether the caller needs separate lines or one string with line breaks; those are different return contracts.
from textwrap import wrap, fill
text = "alpha beta gamma delta"
lines = wrap(text, width=11)
paragraph = fill(text, width=11)
print(lines)
print(paragraph)
print(paragraph == "\n".join(lines))
# ✅ Expected output:
# ['alpha beta', 'gamma delta']
# alpha beta
# gamma delta
# Truewrap returns a list without trailing newlines on its elements. fill returns the joined string. Neither writes to a file or terminal by itself. A width is a formatting instruction, not a change to the original string, which remains available for another format.
from textwrap import wrap
wrap("alpha beta", width=0)
# ✅ Expected error:
# ValueError: invalid width 0 (must be > 0)Whitespace normalization can erase paragraph boundaries
from textwrap import fill
text = "alpha beta\n\ngamma\t delta"
print(fill(text, width=40))
paragraphs = text.split("\n\n")
print([fill(paragraph, width=12) for paragraph in paragraphs])
# ✅ Expected output:
# alpha beta gamma delta
# ['alpha beta', 'gamma\ndelta']By default tabs are expanded and certain whitespace characters, including line breaks, are replaced with spaces. Wrapping one string is not the same as preserving a document’s blank-line-separated paragraphs. Split paragraphs explicitly when that structure matters, format each one and join them with the intended separator.
This is plain-text formatting, not an HTML or Markdown parser. Rewrapping source that contains a code block, table or significant indentation can change its meaning. Keep structured content in its own representation and wrap only the prose fields you intend to reflow.
Long words and hyphens need an explicit policy
from textwrap import wrap
text = "short extraordinary end"
print(wrap(text, width=8))
print(wrap(text, width=8, break_long_words=False))
print(wrap("well-known", width=6, break_on_hyphens=False,
break_long_words=False))
# ✅ Expected output:
# ['short ex', 'traordin', 'ary end']
# ['short', 'extraordinary', 'end']
# ['well-known']The default permits breaking long words so a line can fit. Disabling that behavior preserves a long token even if the resulting line exceeds width. Hyphen breakpoints are controlled separately. Choose the policy for the content: splitting a long prose word may be acceptable while splitting an identifier can make it harder to copy.
Width is based on string character counts, not rendered pixels or terminal display cells. Wide characters, combining marks, tabs and ANSI control sequences can make visual width differ. Do not present textwrap as a complete terminal-layout engine or use it to predict browser line breaks.
from textwrap import wrap
composed = "é"
decomposed = "e\u0301"
print(len(composed))
print(len(decomposed))
print([len(line) for line in wrap("alpha beta", width=5)])
# ✅ Expected output:
# 1
# 2
# [5, 4]The two forms can look similar while having different lengths. Strings, Bytes & Unicode Encodings owns Unicode representation and normalization. For textwrap, the consequence is that a character-count limit is not a visual measurement.
Indentation uses part of the width budget
from textwrap import TextWrapper
wrapper = TextWrapper(width=18, initial_indent="* ", subsequent_indent=" ")
lines = wrapper.wrap("Review the draft and record one concrete correction.")
print("\n".join(lines))
print(all(len(line) <= 18 for line in lines))
# ✅ Expected output:
# * Review the draft
# and record one
# concrete
# correction.
# TrueBoth initial_indent and subsequent_indent count toward the width. The available room for words is therefore smaller than the nominal width. Use a hanging indent for a list item so continuation lines line up with its text rather than its marker.
from textwrap import TextWrapper
wrapper = TextWrapper(width=9)
print(wrapper.wrap("one two three"))
wrapper.width = 5
print(wrapper.wrap("one two three"))
# ✅ Expected output:
# ['one two', 'three']
# ['one', 'two', 'three']A TextWrapper holds reusable settings. Changing an attribute affects subsequent calls, so do not share one mutable wrapper between unrelated tasks while assuming each task has independent configuration. Reuse it when the shared policy is intentional.
shorten collapses whitespace before truncating whole words
from textwrap import shorten
text = " alpha beta\n gamma delta "
print(shorten(text, width=16, placeholder="..."))
print(shorten(text, width=40, placeholder="..."))
print(len(shorten(text, width=16, placeholder="...")))
# ✅ Expected output:
# alpha beta...
# alpha beta gamma delta
# 13shorten first collapses whitespace and then drops trailing words until the result plus placeholder fits. Even if no truncation is necessary, whitespace has already been normalized. The placeholder is part of the total budget, not extra text added beyond width. A shortened preview should not replace the underlying full text.
from textwrap import shorten
shorten("alpha beta", width=2, placeholder="...")
# ✅ Expected error:
# ValueError: placeholder too large for max widthDo not use shorten to retain the first exact number of characters or to preserve all original spacing. Those are slicing or parsing contracts. Choose the operation based on what information may be discarded.
dedent removes a shared margin, not every line’s indentation
from textwrap import dedent
text = " heading\n detail\n ending\n"
print(repr(dedent(text)))
print(repr(text.strip()))
# ✅ Expected output:
# 'heading\n detail\nending\n'
# 'heading\n detail\n ending'dedent removes the common leading whitespace margin from nonblank lines. Extra indentation on the detail line remains relative to the heading. strip removes whitespace only from the outer ends of the entire string, so it does not perform the same job on each line.
from textwrap import dedent
text = "\talpha\n beta\n"
print(repr(dedent(text)))
# ✅ Expected output:
# '\talpha\n beta\n'The lines start with different whitespace characters, so they do not share the same margin. Expand tabs using a deliberate tab size first if the input format says those columns should be treated equivalently. Do not silently normalize indentation in a language where it carries meaning.
indent skips blank lines unless a predicate says otherwise
from textwrap import indent
text = "alpha\n\nbeta\n"
print(repr(indent(text, "> ")))
print(repr(indent(text, "> ", predicate=lambda line: True)))
# ✅ Expected output:
# '> alpha\n\n> beta\n'
# '> alpha\n> \n> beta\n'The default prefixes lines containing non-whitespace characters. A predicate receives each line and decides whether it should be prefixed. This gives you control over blank separator lines in a quoted block or a report. Existing line endings are retained; indent is not a wrapping operation.
Complete a bounded notice preview
Use a reusable wrapper with a first-line marker and aligned continuation lines. Then shorten a separate preview to a total width of 16 characters. The hints provide the continuation indent and the shortening function.
from textwrap import TextWrapper, shorten
wrapper = TextWrapper(width=16, initial_indent="* ", subsequent_indent=___)
text = "Review every changed example before publication."
print(wrapper.fill(text))
print(___(text, width=16, placeholder="..."))
# 👉 replace ___ with " "
# 👉 replace ___ with shorten
# ✅ Expected output:
# * Review every
# changed
# example before
# publication.
# Review every...Format a two-paragraph notice without losing its structure
Given two plain-text paragraphs, wrap each to width 24, preserve one blank line between them, and prefix only nonblank output lines with a vertical bar and a space. Create a separate 20-character preview with an ellipsis placeholder. Print both the full notice and the preview; keep the original paragraph strings unchanged.
from textwrap import fill, indent, shorten
paragraphs = [
"The draft is ready for a careful review.",
"Check the examples and record any corrections."
]
formatted = "\n\n".join(fill(paragraph, width=24) for paragraph in paragraphs)
notice = indent(formatted, "| ")
preview = shorten(" ".join(paragraphs), width=20, placeholder="...")
print(notice)
print("preview:", preview)
print(len(paragraphs))
# ✅ Expected output:
# | The draft is ready for a
# | careful review.
#
# | Check the examples and
# | record any corrections.
# preview: The draft is...
# 2
Practice quiz
What does this program print? from textwrap import wrap print(wrap("one two three", width=7))
- ['one two', 'three']
- 'one two three'
- ['one', 'two', 'three']
- ['one two three']
Answer: ['one two', 'three']. wrap returns a list of fitted lines, not a joined string.
What does this program print? from textwrap import fill print(repr(fill("one two", width=3)))
- ['one', 'two']
- 'one two'
- 'one two'
- 'one two '
Answer: 'one two'. fill joins wrapped lines with newlines and adds no final newline.
When can a wrapped line exceed width?
- Never under any settings
- Only when text contains a comma
- When an overlong token is kept intact with breaking disabled
- Whenever wrap returns a list
Answer: When an overlong token is kept intact with breaking disabled. Preserving an unbreakable word can override the desired line width.
What does this program print? from textwrap import shorten print(shorten(" alpha beta ", width=30))
- alpha beta
- alpha beta
- alpha [...]
- alpha beta
Answer: alpha beta. Whitespace normalization happens even when truncation is unnecessary.
What does this program print? from textwrap import dedent print(repr(dedent(" A B ")))
- 'A B '
- 'A B '
- ' A B'
- 'A B'
Answer: 'A B '. The shared two-space margin is removed while relative indentation remains.
Does an initial indent use part of a TextWrapper width?
- No, it is added after the width limit
- Yes, its characters count toward the line width
- Only when it contains a tab
- Only for subsequent lines
Answer: Yes, its characters count toward the line width. Indent strings are included in the width calculation.
What does this program print? from textwrap import indent print(repr(indent("A B", "> ")))
- '> A > > B'
- 'A B'
- '> A > B'
- '> A B'
Answer: '> A > B'. The default leaves the blank line unprefixed.
What does textwrap width measure?
- Rendered browser pixels
- Terminal display cells in every locale
- UTF-8 byte count
- Python string characters, with formatting rules
Answer: Python string characters, with formatting rules. Character counts do not equal every visual rendering width.
Continue this course
- Previous: Binary Data with struct
- Next: Benchmarking with timeit — Measure tiny code snippets accurately and compare approaches
- Quick reference: Python cheat sheet