25 XP

1. Reverse the words

Beginner strings lists

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

Inputsentence = "Python is fun"
Output"fun is Python"
Explanation"Python", "is", "fun" in reverse order.

Example 2

Inputsentence = " hello world "
Output"world hello"
ExplanationThe extra spaces are dropped.

Example 3

Inputsentence = "hello"
Output"hello"
ExplanationA single word stays as it is.

Constraints

  • sentence has 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).

Code
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