Python

Python textwrap — Wrap, Fill, Dedent, Indent, and Shorten

Terminal output, help text, comments, and plain-text reports all need paragraphs that fit a fixed width and blocks of text with clean margins. The textwrap module does this work with five small functions: wrap and fill reflow a paragraph, dedent removes shared indentation, indent adds a prefix to chosen lines, and shorten cuts a string down to size. This guide takes each one in turn, then the wrapper options, hanging indents, and the input traps.

Written November 14, 2026 · Tested with Python 3.12.3 · 10 min read

By the end of this guide
  • The main program: wrap and fill
  • dedent: remove the indentation a block shares
  • indent: add a prefix to chosen lines
  • shorten: cut a string to whole words

Written November 14, 2026

Tested with Python 3.12.3

What this guide is

The textwrap module formats plain text. Its core work is wrapping: take a paragraph of any length and break it into lines that fit a width, measured in characters. Two functions share that work, wrap returning a list of lines and fill returning the same lines joined into one string. Three helpers cover the jobs that sit next to wrapping: dedent removes indentation that a whole block shares, indent adds a prefix to lines, and shorten cuts a string down to a width without splitting a word. A TextWrapper object holds the settings when the defaults are not the ones the job needs.

The main program: wrap and fill

wrap takes the text and a width and returns one string per line, with no line longer than the width. fill is wrap plus a join on newline characters, so it returns a single string ready to print. Called with no width, both use the default of 70:

Python
import textwrap
text = "The quick brown fox jumps over the lazy dog and keeps running across the field"
print(textwrap.wrap(text, width=30))
print(textwrap.fill(text, width=30))
print(textwrap.wrap(text))

The exact output:

Output
['The quick brown fox jumps over', 'the lazy dog and keeps running', 'across the field']
The quick brown fox jumps over
the lazy dog and keeps running
across the field
['The quick brown fox jumps over the lazy dog and keeps running across', 'the field']

The list form suits code that handles lines one at a time, such as writing each line to a file or drawing each line on a screen. The string form suits a print. Neither function adds a trailing newline, and neither keeps the line breaks the input already had: the paragraph is reflowed as one block of words, and existing newlines count as spaces. Text with real paragraph breaks is wrapped one paragraph at a time.

dedent: remove the indentation a block shares

Text written inside code picks up the code's indentation. A triple-quoted string inside a function carries the function's indent on every line, and printing it as-is prints the indent too. dedent finds the longest common leading whitespace across all lines and removes it, so the block keeps its own inner structure and loses only the shared margin:

Python
import textwrap
block = """
    def greet():
        print("hello")
        print("world")
"""
print(repr(textwrap.dedent(block)))
mixed = "  one\n    two\n  three\n"
print(repr(textwrap.dedent(mixed)))
print(repr(textwrap.dedent("no indent")))

The exact output:

Output
'\ndef greet():\n    print("hello")\n    print("world")\n'
'one\n  two\nthree\n'
'no indent'

The mixed block shows the rule at work: two spaces were common to all three lines, so two spaces came off each, and the middle line kept the two extra spaces that were its own. Lines that are empty or hold only whitespace do not count when the common prefix is worked out, and they come out empty. A block with no shared indentation passes through unchanged. dedent is the standard fix for help text, report templates, and sample output written as literals inside functions.

indent: add a prefix to chosen lines

indent does the opposite job. It adds a prefix to the front of lines in a block, which is how a program quotes text in a reply, comments out a block, or marks lines in a log. By default every non-empty line gets the prefix and blank lines stay blank. A third argument, a predicate function, picks the lines instead: a line gets the prefix only when the predicate returns true for it:

Python
import textwrap
text = "first\n\nsecond"
print(textwrap.indent(text, "> "))
notes = "keep\n# note\nkeep two\n# note two"
print(textwrap.indent(notes, "  ", lambda line: line.startswith("#")))

The exact output:

Output
> first

> second
keep
  # note
keep two
  # note two

The blank line in the first block stayed blank, with no prefix and no trailing spaces after it. The predicate form is a per-line decision, so any test the program can write works: lines that start with a marker, lines longer than a limit, or every second line with a counter in a closure. Lines that fail the test pass through exactly as they were.

shorten: cut a string to whole words

shorten cuts a string down so the result, plus a placeholder marking the cut, fits a width. It cuts at a word boundary, never inside a word, and the placeholder counts against the width. A string that already fits comes back as it was, apart from collapsed whitespace. A width too small to hold the placeholder itself raises an error rather than returning a misleading result:

Python
import textwrap
print(repr(textwrap.shorten("The quick brown fox jumps over the lazy dog", width=20)))
print(repr(textwrap.shorten("The quick brown fox", width=30)))
print(repr(textwrap.shorten("Hello world", width=8, placeholder="...")))
try:
    textwrap.shorten("Hello world", width=2)
except ValueError as e:
    print("ValueError:", e)

The exact output:

Output
'The quick [...]'
'The quick brown fox'
'Hello...'
ValueError: placeholder too large for max width

The default placeholder is [...], brackets and space included, which is why a width of 20 left room for two whole words plus the marker. shorten suits one-line summaries: list rows, menu labels, and log lines where the full text exists somewhere else and the cut only needs to be honest. It works on one line at a time and does not wrap, so a long input needs wrap first if more than the opening words matter.

TextWrapper: long words, hyphens, and tabs

The module-level functions take the common settings as arguments. For the rest, build a TextWrapper with the settings as its own arguments and call its wrap or fill. Three settings change how text breaks. break_long_words decides whether a word longer than the width is split across lines; break_on_hyphens decides whether a hyphenated word can break after the hyphen. Tabs are expanded to spaces before wrapping, up to the next multiple of 8 columns, unless expand_tabs is off, in which case the whitespace step turns each tab into one space:

Python
import textwrap
w = textwrap.TextWrapper(width=20, break_long_words=False, break_on_hyphens=False)
print(w.wrap("a supercalifragilisticexpialidocious word and well-known facts stay whole"))
w2 = textwrap.TextWrapper(width=20)
print(w2.wrap("a supercalifragilisticexpialidocious word"))
print(textwrap.wrap("one\ttwo three four five six", width=12))
print(textwrap.wrap("one\ttwo three four five six", width=12, expand_tabs=False))

The exact output:

Config
['a', 'supercalifragilisticexpialidocious', 'word and well-known', 'facts stay whole']
['a supercalifragilist', 'icexpialidocious', 'word']
['one     two', 'three four', 'five six']
['one two', 'three four', 'five six']

With both break settings off, the long word takes a line of its own and runs past the width rather than split, and well-known stays whole. With the defaults, the long word splits at the width. The tab rows show the two tab paths: expanded, the tab became the five spaces that carry column 3 to column 8; not expanded, it became a single space. A wrapper object holds no text, so one wrapper with fixed settings can format many paragraphs in a loop.

Hanging indents: the first line differs from the rest

initial_indent prefixes the first line and subsequent_indent prefixes every line after it. The indents count against the width, so the text area on a prefixed line is the width minus the indent. The pair builds the shapes reference text uses: a term followed by an indented definition, or a marker on the first line with the continuation lines aligned under the text:

Python
import textwrap
text = "term: the definition of the term keeps going onto the next line"
print(textwrap.fill(text, width=32, initial_indent="", subsequent_indent="      "))
print(textwrap.fill(text, width=32, initial_indent=">> ", subsequent_indent=".. "))

The exact output:

Output
term: the definition of the term
      keeps going onto the next
      line
>> term: the definition of the
.. term keeps going onto the
.. next line

The second call shows that the two indents are independent strings: the first line carries one marker and the rest carry another. These arguments exist on the module-level functions as well as on TextWrapper, so a one-off format does not need an object. List markers, error prefixes, and quoted blocks are all this same pair of settings with different strings.

The traps: empty input, one long word, and leading spaces

Trap
Three results surprise on first sight. Empty input is not an error: wrap returns an empty list and fill returns an empty string. A single word longer than the width leaves shorten nothing it can keep, so the result is the placeholder alone, cut to the width. And leading spaces at the very start of the text survive the wrap on the first line, because the whitespace that wrapping drops is the whitespace at line breaks, not the start of the text:
Python
import textwrap
print(textwrap.wrap(""))
print(textwrap.wrap("   "))
print(repr(textwrap.fill("")))
print(repr(textwrap.shorten("supercalifragilistic", width=10)))
print(textwrap.wrap("  leading spaces kept or not", width=12))
print(textwrap.wrap("word " * 3, width=100))

The exact output:

Config
[]
[]
''
'[...]'
['  leading', 'spaces kept', 'or not']
['word word word']

The fixes match the causes. Test for empty text before wrapping when an empty result would break the code that reads the lines. Give shorten a width that can hold at least one word plus the placeholder when one word must always show. Strip the text first when leading spaces are not wanted, since the wrapper treats them as content. The last row shows the other end of the same rule: runs of whitespace inside the text collapse to one space, and the trailing space at the end is dropped.

Which choice for which job

Job Choice Why
Lines as a list wrap One string per line
One printable string fill Lines joined with newlines
Clean a literal block's margin dedent Removes only the shared prefix
Prefix lines indent Predicate picks the lines
One-line summary with a cut marker shorten Whole words plus placeholder
Repeated formats with set rules TextWrapper Settings held in one object
Term and definition shapes initial_indent + subsequent_indent First line differs from the rest

Checklist

  • Wrap one paragraph at a time; existing line breaks are treated as spaces, not paragraph marks.
  • Pick wrap when the lines are data and fill when the result is printed as one string.
  • Run dedent on triple-quoted literals before printing them from inside a function.
  • Use the indent predicate when only some lines take the prefix; blank lines stay blank either way.
  • Check that a shorten width can hold the placeholder, and handle the error when it cannot.
  • Set break_long_words and break_on_hyphens off when long words and hyphenated terms must stay whole.
  • Handle empty input before wrapping, since the empty result is a valid empty list or string.

Sources

Keep Exploring