textwrap wraps, fills, indents, and truncates text in Python. Standard library — no install. import textwrap. Wrap: textwrap.wrap("Long text...", width=40) → list of strings. Fill: textwrap.fill("Long text...", width=40) → single wrapped string. Shorten: textwrap.shorten("Long text", width=20, placeholder="...") → truncated with placeholder. Dedent: textwrap.dedent(""" indented""") → removes common leading whitespace. Indent: textwrap.indent("text\nmore", prefix=" ") → adds prefix to each line. textwrap.indent(text, prefix="# ", predicate=lambda l: l.strip()) — conditional prefix. TextWrapper: w = textwrap.TextWrapper(width=72, initial_indent=" ", subsequent_indent=" "). w.wrap(text) / w.fill(text). Options: break_long_words=False — never break within a word (may exceed width). break_on_hyphens=False — keep hyphenated words intact. expand_tabs=True — expand tabs to spaces. tabsize=4. max_lines=5 — limit output lines. fix_sentence_endings=True — add extra space after ”. ”. Drop whitespace: drop_whitespace=True (default). Long word: by default long words are broken; break_long_words=False preserves URLs. CLI: use fill(textwrap.dedent(docstring).strip(), width=shutil.get_terminal_size().columns - 4). Claude Code generates textwrap formatters, CLI help renderers, and paragraph layout tools.
CLAUDE.md for textwrap
## textwrap Stack
- stdlib — no install | import textwrap
- wrap: textwrap.wrap(text, width=72) → list[str]
- fill: textwrap.fill(text, width=72) → str (joined with newlines)
- shorten: textwrap.shorten(text, width=40, placeholder="...") — truncate
- dedent: textwrap.dedent(text) — strip common leading whitespace
- indent: textwrap.indent(text, prefix=" ") — add prefix to lines
- TextWrapper(width, initial_indent, subsequent_indent, break_long_words=False)
textwrap Text Formatting Pipeline
# app/text_format.py — textwrap wrapping, indentation, and CLI paragraph tools
from __future__ import annotations
import shutil
import textwrap
from typing import Callable
# ─────────────────────────────────────────────────────────────────────────────
# Terminal width helper
# ─────────────────────────────────────────────────────────────────────────────
def terminal_width(fallback: int = 80, margin: int = 2) -> int:
"""Return the current terminal width minus a margin."""
return shutil.get_terminal_size((fallback, 24)).columns - margin
# ─────────────────────────────────────────────────────────────────────────────
# 1. Core wrappers
# ─────────────────────────────────────────────────────────────────────────────
def wrap(text: str, width: int = 72) -> list[str]:
"""
Wrap text at word boundaries, returning a list of lines.
Long URLs and words are not broken (break_long_words=False).
"""
return textwrap.wrap(text, width=width, break_long_words=False, break_on_hyphens=False)
def fill(text: str, width: int = 72) -> str:
"""
Wrap text and return as a single joined string with newlines.
Equivalent to "\n".join(wrap(text, width)).
"""
return textwrap.fill(text, width=width, break_long_words=False, break_on_hyphens=False)
def fill_terminal(text: str, margin: int = 4) -> str:
"""
Fill text to the current terminal width.
Useful for CLI output that should respect the user's window size.
"""
width = terminal_width(margin=margin)
return fill(text, width=width)
def shorten(text: str, width: int = 80, placeholder: str = "...") -> str:
"""
Truncate text to at most `width` characters, appending placeholder.
Truncates at a word boundary.
"The quick brown fox jumps over the lazy dog" → "The quick brown..." (width=20)
"""
return textwrap.shorten(text, width=width, placeholder=placeholder)
# ─────────────────────────────────────────────────────────────────────────────
# 2. Indentation helpers
# ─────────────────────────────────────────────────────────────────────────────
def indent(text: str, prefix: str = " ", skip_empty: bool = True) -> str:
"""
Prefix each line with `prefix`.
skip_empty=True (default): don't add prefix to blank lines.
"""
predicate = (lambda line: line.strip()) if skip_empty else None
return textwrap.indent(text, prefix=prefix, predicate=predicate)
def dedent(text: str) -> str:
"""
Remove common leading whitespace from all non-empty lines.
Use for stripping indentation from triple-quoted docstrings.
"""
return textwrap.dedent(text)
def normalize_docstring(docstring: str) -> str:
"""
Clean up a PEP-257 docstring:
1. Strip leading/trailing blank lines
2. Dedent common whitespace
3. Return clean text
"""
return textwrap.dedent(docstring).strip()
def comment_block(text: str, prefix: str = "# ", width: int = 72) -> str:
"""
Wrap text and prefix each line to create a comment block.
"This is a note" → "# This is a note\n# continued here"
"""
wrapped = textwrap.fill(text, width=width - len(prefix), break_long_words=False)
return textwrap.indent(wrapped, prefix=prefix)
def blockquote(text: str, width: int = 72) -> str:
"""Format text as a Markdown blockquote ("> " prefix)."""
return comment_block(text, prefix="> ", width=width)
# ─────────────────────────────────────────────────────────────────────────────
# 3. Hanging indent (for CLI option descriptions)
# ─────────────────────────────────────────────────────────────────────────────
def hanging_indent(
text: str,
width: int = 72,
first_indent: str = "",
rest_indent: str = " ",
) -> str:
"""
Wrap with a hanging indent: first line has first_indent, rest get rest_indent.
Useful for option help text:
"--verbose Enable verbose output and show all
intermediate processing steps"
"""
return textwrap.fill(
text,
width=width,
initial_indent=first_indent,
subsequent_indent=rest_indent,
break_long_words=False,
break_on_hyphens=False,
)
def format_option_help(option: str, description: str, width: int = 72) -> str:
"""
Format a CLI option with its description in a hanging-indent style.
format_option_help("--verbose", "Enable verbose logging") →
"--verbose Enable verbose logging and show all\n intermediate steps"
"""
col = max(len(option) + 2, 12)
first = f"{option:<{col}}{description}"
indent_str = " " * col
return textwrap.fill(
first,
width=width,
initial_indent="",
subsequent_indent=indent_str,
break_long_words=False,
)
# ─────────────────────────────────────────────────────────────────────────────
# 4. Multi-paragraph formatting
# ─────────────────────────────────────────────────────────────────────────────
def wrap_paragraphs(text: str, width: int = 72) -> str:
"""
Wrap each paragraph independently, preserving blank lines between them.
Input paragraphs separated by blank lines remain separated.
"""
paragraphs = text.split("\n\n")
wrapped = []
for para in paragraphs:
stripped = para.strip()
if stripped:
wrapped.append(fill(stripped, width=width))
else:
wrapped.append("")
return "\n\n".join(wrapped)
def format_list(items: list[str], width: int = 72, bullet: str = "• ") -> str:
"""
Format a list with bullet points, wrapping each item's text.
Items that wrap get a hanging indent aligned after the bullet.
"""
lines = []
hang = " " * len(bullet)
for item in items:
wrapped = textwrap.fill(
item,
width=width,
initial_indent=bullet,
subsequent_indent=hang,
break_long_words=False,
)
lines.append(wrapped)
return "\n".join(lines)
def format_numbered_list(items: list[str], width: int = 72, start: int = 1) -> str:
"""
Format a numbered list: "1. ", "2. ", etc.
Numbers beyond 9 are padded to keep alignment.
"""
pad = len(str(len(items) + start - 1)) + 2 # "1. " = 3, "10. " = 4
lines = []
for i, item in enumerate(items, start):
prefix = f"{i}. "
hang = " " * pad
wrapped = textwrap.fill(
item,
width=width,
initial_indent=prefix.ljust(pad),
subsequent_indent=hang,
break_long_words=False,
)
lines.append(wrapped)
return "\n".join(lines)
# ─────────────────────────────────────────────────────────────────────────────
# 5. Table of fixed-width columns
# ─────────────────────────────────────────────────────────────────────────────
def format_two_column(
rows: list[tuple[str, str]],
col1_width: int = 20,
total_width: int = 72,
separator: str = " ",
) -> str:
"""
Format a list of (label, description) pairs as a two-column layout.
Labels truncated at col1_width; descriptions wrapped to fill remaining space.
"""
col2_width = total_width - col1_width - len(separator)
lines = []
for label, desc in rows:
label_str = label[:col1_width].ljust(col1_width)
desc_lines = textwrap.wrap(desc, width=col2_width, break_long_words=False) or [""]
first = f"{label_str}{separator}{desc_lines[0]}"
lines.append(first)
pad = " " * (col1_width + len(separator))
for dl in desc_lines[1:]:
lines.append(f"{pad}{dl}")
return "\n".join(lines)
# ─────────────────────────────────────────────────────────────────────────────
# 6. Jinja2 filter registration
# ─────────────────────────────────────────────────────────────────────────────
def register_textwrap_filters(env, default_width: int = 72) -> None:
"""
Register textwrap filters for Jinja2.
Usage:
{{ post.body | wordwrap(72) }}
{{ title | truncate_words(20) }}
{{ code | indent_text(" ") }}
"""
env.filters["wordwrap"] = lambda t, w=default_width: fill(t, width=w)
env.filters["truncate_words"] = lambda t, w=80: shorten(t, width=w)
env.filters["indent_text"] = lambda t, p=" ": indent(t, prefix=p)
env.filters["dedent"] = dedent
env.filters["blockquote"] = lambda t, w=default_width: blockquote(t, width=w)
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
LONG_TEXT = (
"Python's textwrap module provides convenient functions for "
"wrapping and formatting plain text, making it easier to produce "
"output that looks good in a fixed-width terminal or printed "
"document. The TextWrapper class allows fine-grained control "
"over breaking behavior, indentation, and line limits."
)
print("=== fill(width=60) ===")
print(fill(LONG_TEXT, width=60))
print("\n=== shorten ===")
for width in [40, 60, 80]:
print(f" w={width}: {shorten(LONG_TEXT, width=width)!r}")
print("\n=== indent ===")
code = "def hello():\n print('hi')\n return True"
print(indent(code, prefix=" "))
print("\n=== dedent ===")
indented = """
This has common
leading spaces
on every line.
"""
print(repr(dedent(indented).strip()))
print("\n=== comment_block ===")
print(comment_block(LONG_TEXT, prefix="# ", width=60))
print("\n=== blockquote ===")
print(blockquote("This is a quoted passage that wraps nicely.", width=50))
print("\n=== hanging_indent ===")
print(hanging_indent(LONG_TEXT, width=60, first_indent="", rest_indent=" "))
print("\n=== format_option_help ===")
options = [
("--verbose", "Enable verbose logging output"),
("--output FILE", "Write results to FILE instead of stdout"),
("--max-retries N", "Maximum number of retry attempts on failure (default: 3)"),
]
for opt, desc in options:
print(format_option_help(opt, desc, width=60))
print()
print("=== format_list ===")
items = [
"First item with a longer description that might wrap at the margin",
"Second item",
"Third item with even more text to demonstrate the hanging indent behavior in list formatting",
]
print(format_list(items, width=60))
print("\n=== format_numbered_list ===")
print(format_numbered_list(items, width=60))
print("\n=== format_two_column ===")
data = [
("--help", "Show help message and exit"),
("--verbose", "Enable verbose mode with extra output"),
("--output", "Output file path"),
("--max-workers", "Number of parallel workers (default 4)"),
]
print(format_two_column(data, col1_width=18, total_width=60))
For the shutil.get_terminal_size alternative — shutil.get_terminal_size() gives you the terminal columns but doesn’t wrap text; textwrap does the wrapping — they’re complementary: use terminal_size for the width, textwrap.fill for the layout, which is what fill_terminal() combines in one call. For the rich.text.Text alternative — rich provides rich text with color, bold, tables, and panels; textwrap is the right choice when you want plain wrapping with no dependencies (CLI tools that don’t require color, log output, file generation) or when you’re wrapping text before passing it to another renderer — rich printing and textwrap filling are complementary, not competing. The Claude Skills 360 bundle includes textwrap skill sets covering textwrap.wrap() list output, textwrap.fill() string output, textwrap.shorten() with placeholder, textwrap.dedent() docstring cleanup, textwrap.indent() with predicate, TextWrapper with initial_indent/subsequent_indent, fill_terminal() for dynamic terminal width, format_option_help() hanging-indent CLI options, wrap_paragraphs() multi-paragraph formatter, format_list() bullet list with hanging indent, format_numbered_list() numbered list, format_two_column() label-description layout, and Jinja2 filter registration. Start with the free tier to try text wrapping and formatting code generation.