On this page
  1. textwrap
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Wrapping & Prefixing Multi-Line CLI Output (fill + indent)
  7. 2. Custom Line Filtering in indent()
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

textwrap

Prev: termios | Up: stdlib_module | Next: this
Rel: string, re, difflib, unicodedata, stringprep
Ref: docs.python.org — textwrap
Tags: #public #python3 #stdlib


Import

import textwrap

Overview

Paragraph wrapping, indentation, dedentation, and truncation utilities (dedent, indent, fill, wrap, shorten). Reach for textwrap.dedent() for clean multi-line triple-quoted strings inside indented functions and tests, indent() for prefixing blocks, and shorten() for word-boundary summaries.

Quick Start

import textwrap

block = textwrap.dedent('''
    line one
        indented line two
''').lstrip("\n")
assert block == "line one\n    indented line two\n"

assert textwrap.shorten("Python standard library utilities", width=20, placeholder="...") == "Python standard..."

Implementation Walkthrough

1. Wrapping & Prefixing Multi-Line CLI Output (fill + indent)

import textwrap

body = "A long diagnostic message explaining why a configuration file failed validation."
wrapped = textwrap.fill(body, width=40)
quoted = textwrap.indent(wrapped, prefix="  > ")
assert all(line.startswith("  > ") for line in quoted.splitlines())

2. Custom Line Filtering in indent()

Pass a predicate= callable to indent even blank lines (by default, indent() skips whitespace-only lines):

import textwrap

assert textwrap.indent("a\n\nb", "> ", predicate=lambda _: True) == "> a\n> \n> b"

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes