Wrap text to a label width
A shipping label printer takes a fixed number of characters per line, and a description has to be broken across lines without splitting words.
- Fill each line greedily: keep adding words while they still fit.
- Words are separated by whitespace and joined back with a single space.
- A word longer than the whole width goes on a line of its own, unbroken.
- A width of zero or less, or text with no words, gives an empty list.
word_wrap(text: string, width: int) → list<string>
Where you start
def word_wrap(text: str, width: int) -> list[str]:
Worked examples
| Call | Result |
|---|---|
word_wrap("the quick brown fox", 10) | ["the quick", "brown fox"] |
word_wrap("a bb ccc", 3) | ["a", "bb", "ccc"] |
word_wrap("supercalifragilistic is long", 5) | ["supercalifragilistic", "is", "long"] |
word_wrap("one two", 20) | ["one two"] |
Hint
Track the current line as a string. Before adding a word, check whether the line plus a space plus the word still fits.
Reference solution in Python
def word_wrap(text: str, width: int) -> list[str]:
if width <= 0:
return []
lines = []
line = ''
for w in text.split():
if line == '':
line = w
elif len(line) + 1 + len(w) <= width:
line += ' ' + w
else:
lines.append(line)
line = w
if line:
lines.append(line)
return lines