65. Word wrap
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: exactlywidthcharacters is fine. - A word never breaks in two. A word longer than
widthgoes 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
[]. widthis optional: when it isn't given, it is 20. Write that as a default value in thedefline.
Example 1
Input
text = "The quick brown fox jumps over the dog",
width = 10Output
["The quick", "brown fox", "jumps over",
"the dog"]ExplanationEach line holds what fits in 10 characters.
Example 2
Input
text = "it is extraordinary", width = 8Output
["it is", "extraordinary"]ExplanationThe long word gets a line of its own.
Example 3
Input
text = "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
texthas 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).
text.split()gives the words, however many spaces are between them. Build the current line, and a list of finished lines.- A word joins the current line if
len(line) + 1 + len(word) <= width(the 1 is the space). Otherwise the line is finished and the word starts the next one. The first word of a line needs no space. - Don't forget the last line when the words run out, unless it is empty.
textwrap.wrap()from the standard library breaks long words apart, which isn't what is asked.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.