How to wrap a string into lines of width w in Python

2 Answers

0 votes
"""
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.
 
"""

 



answered 9 hours ago by avibootz
edited 3 hours ago by avibootz
0 votes
import textwrap

def wrap_text(text, width):
    return textwrap.fill(text, width)

def main():
    s = (
        "Python provides excellent built-in tools for text wrapping. "
        "Using textwrap ensures clean, efficient, and good code."
    )
    w = 35

    wrapped = wrap_text(s, w)
    print("Wrapped text:\n")
    print(wrapped)

if __name__ == "__main__":
    main()



'''
run:

Wrapped text:

Python provides excellent built-in
tools for text wrapping. Using
textwrap ensures clean, efficient,
and good code.

'''

 



answered 2 hours ago by avibootz
...