Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Wrap text to a fixed line width

Break a string into lines no longer than a given width, breaking on spaces when possible.

Python practice30 minString PatternsAdvancedLast updated March 18, 2026

Problem statement

Write wrap_text(text, width) that returns a string with newline characters inserted so that each output line has length <= width. Treat existing newline characters as paragraph separators: wrap each paragraph independently and preserve blank lines. When possible, break lines at whitespace between words; if a single word is longer than width, split the word into chunks of size width. Width must be an integer >= 1. Collapse consecutive whitespace between words into a single space when wrapping (i.e., treat words as separated by any whitespace).

Task

Implement a function that wraps text to a maximum line width, preserving existing paragraph breaks and splitting long words when necessary.

Examples

Simple wrapping at word boundaries

Input

wrap_text('The quick brown fox', 10)

Output

'The quick\nbrown fox'

First line 'The quick' length 9 <= 10, second line contains remaining words.

Breaking long words

Input

wrap_text('Supercalifragilisticexpialidocious', 10)

Output

'Supercalif\nragilistic\nexpialidoc\nious'

A single long word is split into chunks of width 10.

Input format

text (string), width (int >= 1).

Output format

A string with newline separators such that each line's length <= width.

Constraints

Do not use external libraries. Preserve blank lines. Collapse internal whitespace into single spaces when wrapping words.

Samples

Sample 1

Input

wrap_text('Hello world', 5)

Output

'Hello\nworld'

Both words fit exactly on separate lines when width is 5.