Word Wrap
Wrap long text at a specified column width, with word or character break options.
About this tool
Text wrapping is a fundamental formatting technique used whenever readability and line length constraints matter. Whether you're preparing documentation, formatting email bodies, or aligning code output to console widths, the Word Wrap tool handles the mechanical task of breaking long lines at sensible points. By setting a target column width—commonly 80 characters, echoing terminals and historical coding standards—you can ensure your text fits neatly within your medium of choice.
The tool offers two distinct modes to match your needs. Word mode respects natural language boundaries, breaking only at spaces to keep words intact; this is ideal for prose, comments, and human-readable text. Character mode, by contrast, cuts precisely at the character limit, useful when you have strict formatting requirements or when working with data formats that need exact column alignment. The tool preserves your original line breaks and blank lines, so it acts as an additive formatter rather than a destructive reflow.
Frequently Asked Questions
Code Implementation
def word_wrap(text: str, width: int = 80, hard: bool = False) -> str:
"""Wrap text to the specified width.
Args:
text: Input text (may contain existing newlines).
width: Maximum line length in characters.
hard: If True, break mid-word at exactly 'width' chars.
"""
import textwrap
if hard:
# Hard wrap: split each existing line at 'width' chars
lines = []
for line in text.splitlines(keepends=True):
while len(line) > width:
lines.append(line[:width] + "\n")
line = line[width:]
lines.append(line)
return "".join(lines)
else:
# Soft wrap: only break at whitespace
paragraphs = text.split("\n\n")
wrapped = [textwrap.fill(p, width=width) for p in paragraphs]
return "\n\n".join(wrapped)
text = ("The quick brown fox jumps over the lazy dog. "
"Pack my box with five dozen liquor jugs. "
"How vexingly quick daft zebras jump!")
print(word_wrap(text, width=40))Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.