Wrap Text to a Fixed Width

Hard ⏱ 18 min 25% acceptance ★★★★☆ 4.3
Write a function wrap_text(text, width) that wraps a single-line string text into multiple lines, each at most width characters long, breaking only at spaces (never splitting a word), and returns the result as one string with lines joined by \n. Assume no single word exceeds width characters.

Examples

Example 1
Input
wrap_text("the quick brown fox jumps", 10)
Output
'the quick\nbrown fox\njumps'
Explanation

Words are packed greedily without exceeding 10 characters per line.

Example 2
Input
wrap_text("hi", 10)
Output
'hi'
Explanation

Fits on one line.

Constraints

  • text has one or more space-separated words; width is a positive int at least as large as the longest word.

Topics

Input & Outputtext wrapping

Companies

AmazonNetflix

Hints

Hint 1

Iterate words, tracking the current line; when adding the next word would exceed width, start a new line.

Hint 2

Watch the "would this line + word (plus a space) exceed width" check carefully for the first word on a line.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.