50 XP

65. Word wrap

Intermediate strings greedy

Write a function wrap(text, width=20) that breaks a text into lines and returns them as a list of strings:

  • Take the words in order and put as many on each line as fit, separated by single spaces. A line fits when its length is at most width: exactly width characters is fine.
  • A word never breaks in two. A word longer than width goes on a line by itself.
  • Words are separated by one or more spaces in text; the lines have no spaces at their ends.
  • A text with no words (empty, or only spaces) gives an empty list [].
  • width is optional: when it isn't given, it is 20. Write that as a default value in the def line.

Example 1

Inputtext = "The quick brown fox jumps over the dog", width = 10
Output["The quick", "brown fox", "jumps over", "the dog"]
ExplanationEach line holds what fits in 10 characters.

Example 2

Inputtext = "it is extraordinary", width = 8
Output["it is", "extraordinary"]
ExplanationThe long word gets a line of its own.

Example 3

Inputtext = "Python is a programming language"
Output["Python is a", "programming language"]
ExplanationNo width given, so 20: the second line is exactly 20 characters long.

Constraints

  • text has 0 to 300 characters: letters, digits, punctuation and spaces.
  • width, when given, is a whole number from 1 to 80.

Submit also runs 9 more tests you can't see.

Practises Function Arguments (lesson 17).

Code
def wrap(text, width=20):
    """Break text into lines of at most width characters.

    text: str, words separated by spaces; may be empty
    width: int, the longest a line may be; 20 if not given
    Returns: list of str, the lines, each word whole
    """
    # Write your code here
    pass