1. Reverse the words
Write a function reverse_words(sentence) that takes a string sentence and returns a new string with the same
words in reverse order: the last word first, the first word last. A word is a group of characters with no spaces in
it. In the result, the words are separated by exactly one space.
Extra spaces between words, or at the start and end, should not end up in the result.
If sentence is empty, or holds only spaces, return an empty string "".
Example 1
sentence = "Python is fun""fun is Python"Example 2
sentence = " hello world ""world hello"Example 3
sentence = "hello""hello"Constraints
sentencehas 0 to 100 characters.- It holds only letters and spaces. Words can be separated by more than one space.
Submit also runs 3 more tests you can't see.
Practises String Methods (lesson 5).
sentence.split(), with nothing in the brackets, gives a list of the words and skips every extra space, at the ends too.- Reverse the list with
words.reverse(), or make a reversed copy with the slicewords[::-1]. " ".join(words)puts the words back into one string with one space between them. An empty list joins to"", so an empty sentence needs no special case.
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.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def reverse_words(sentence):
"""Return the words of a sentence in reverse order.
sentence: str, words separated by one or more spaces
Returns: str, the words last to first, one space apart
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.