Drill

ProblemsPython › text

Wrap text to a label width

hardtextPython

A shipping label printer takes a fixed number of characters per line, and a description has to be broken across lines without splitting words.

word_wrap(text: string, width: int) → list<string>

Solve it in the editor →

Where you start

def word_wrap(text: str, width: int) -> list[str]:
    

Worked examples

CallResult
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

The same problem in another language

More text problems in Python