Claude Code for textwrap: Python Text Wrapping and Formatting — Claude Skills 360 Blog
Blog / AI / Claude Code for textwrap: Python Text Wrapping and Formatting
AI

Claude Code for textwrap: Python Text Wrapping and Formatting

Published: March 5, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free