AI Skill Report Card
Wrapping and Formatting Text
YAML--- name: wrapping-and-formatting-text description: Wraps, fills, shortens, and dedents plain text using Python's textwrap module. Use when formatting long strings into readable paragraphs, wrapping CLI output, truncating text with ellipsis, removing common leading whitespace from multi-line strings, or indenting text blocks. ---
Wrapping and Formatting Text
Uses Python's built-in textwrap module to programmatically wrap, fill, indent, dedent, and shorten text.
Quick Start14 / 15
Pythonimport textwrap text = "The quick brown fox jumps over the lazy dog. " * 3 # Wrap into a list of lines (width in characters) lines = textwrap.wrap(text, width=40) # Wrap and rejoin into a single string with newlines wrapped = textwrap.fill(text, width=40) print(wrapped)
Recommendation▾
Add an example combining dedent+fill together as mentioned in best practices to reinforce the pattern
Workflow14 / 15
Progress:
- Identify the goal: list of lines (
wrap), single string (fill), truncation (shorten), whitespace normalization (dedent), or adding prefixes (indent) - Choose the right function for that goal
- Configure relevant keyword arguments (width, prefixes, break behavior)
- Apply to input text
- Verify output formatting (line lengths, indentation, no unwanted whitespace)
Function selection guide
| Need | Function |
|---|---|
| List of wrapped lines | textwrap.wrap(text, width=70) |
| Single wrapped string | textwrap.fill(text, width=70) |
Truncate to fit width + add [...] | textwrap.shorten(text, width=50) |
| Remove common leading whitespace | textwrap.dedent(text) |
| Add prefix to each line | textwrap.indent(text, prefix) |
| Reusable wrapper with custom settings | textwrap.TextWrapper(**options) |
Key options (for wrap/fill/TextWrapper)
width(default 70) — max line lengthinitial_indent/subsequent_indent— string prepended to first/later linesbreak_long_words(defaultTrue) — split words longer than widthbreak_on_hyphens(defaultTrue) — allow breaking at hyphensreplace_whitespace(defaultTrue) — collapse all whitespace to single spacesdrop_whitespace(defaultTrue) — strip leading/trailing whitespace per linemax_lines— truncate output, adding a placeholder (default' [...]') on the last linetabsize— expand tabs to this many spaces before processing (default 8)
Recommendation▾
Include a brief note on performance/limits with very large texts
Examples19 / 20
Example 1: Wrapping paragraph for terminal output Input:
Pythontextwrap.fill("This is a very long line of text that needs wrapping for a narrow terminal.", width=30)
Output:
This is a very long line of
text that needs wrapping for
a narrow terminal.
Example 2: Dedenting a triple-quoted string Input:
Pythontext = """ def foo(): return 1 """ print(textwrap.dedent(text))
Output:
def foo():
return 1
Example 3: Indenting with a prefix (e.g., for quoting/logging) Input:
Pythontextwrap.indent("line one\nline two", "> ")
Output:
> line one
> line two
Example 4: Shortening text with placeholder Input:
Pythontextwrap.shorten("The quick brown fox jumps over the lazy dog", width=25)
Output:
The quick brown fox [...]
Example 5: Reusable wrapper for hanging indent Input:
Pythonwrapper = textwrap.TextWrapper(width=40, initial_indent="- ", subsequent_indent=" ") print(wrapper.fill("This is a bullet point that wraps onto multiple lines nicely."))
Output:
- This is a bullet point that wraps
onto multiple lines nicely.
Recommendation▾
Consider mentioning textwrap vs alternatives (e.g., third-party libs) for non-monospace or Unicode-aware wrapping edge cases
Best Practices
- Use
dedent()beforefill()/wrap()when processing triple-quoted strings defined inside indented code — combine astextwrap.fill(textwrap.dedent(text)). - Prefer
TextWrapperover repeatedwrap()/fill()calls when applying the same settings many times — it avoids re-parsing options. - Use
initial_indent/subsequent_indentfor bullet points, blockquotes, or comment-style prefixes instead of manual string concatenation. - Set
break_long_words=Falseandbreak_on_hyphens=Falsewhen wrapping text containing URLs, file paths, or code identifiers that shouldn't be split. - Use
shorten()for generating previews/summaries (e.g., truncated log lines, table cells) since it collapses whitespace and adds a clean placeholder automatically.
Common Pitfalls
- Don't use
dedent()on text with mixed tabs/spaces without normalizing first — it only strips leading whitespace common to all lines, so inconsistent indentation results in no-op. - Don't forget
dedent()operates on the whole text as a block; it won't help per-line indentation removal for irregularly indented lines. - Don't assume
wrap()preserves original line breaks —replace_whitespace=True(the default) collapses newlines/tabs into spaces before wrapping. - Don't use
fill()when you need the individual lines for further processing (e.g., adding line numbers) — usewrap()and join manually instead. - Remember
indent()by default adds the prefix to lines consisting solely of whitespace too; pass apredicatefunction to control which lines get prefixed.