"""
String‑wrapping utility using Python's built‑in textwrap module.
We define a function `wrap_text` that:
1. Accepts a string and a desired width.
2. Uses textwrap.fill(), which:
- Breaks long text into lines no longer than `width`.
- Preserves word boundaries.
- Avoids expensive manual loops.
3. Returns the wrapped paragraph as a single string.
This approach is:
- Python: uses Python's standard library instead of reinventing wrapping logic.
- Efficient: textwrap is implemented in optimized Python and C routines.
- Clean: minimal code, clear comments, predictable behavior.
"""
import textwrap
def wrap_text(text: str, width: int) -> str:
"""
Wrap `text` into a paragraph whose lines are at most `width` characters.
Parameters
----------
text : str
The input string to wrap.
width : int
Maximum line width.
Returns
-------
str
A new string containing the wrapped text.
"""
# textwrap.fill() performs the entire wrapping process:
# - Splits text into words
# - Reassembles them into lines <= width
# - Returns a single string with newline separators
return textwrap.fill(text, width=width)
# Usage:
if __name__ == "__main__":
sample = (
"Python provides excellent built-in tools for text wrapping. "
"Using textwrap ensures clean, efficient, and good code."
)
result = wrap_text(sample, 35)
print(result)
"""
run:
Python provides excellent built-in
tools for text wrapping. Using
textwrap ensures clean, efficient,
and good code.
"""