Reverse the order of the words
A text filter turns a sentence back to front, word by word, without disturbing the words themselves.
- Only the order of the words changes; the letters inside each word stay put.
- Runs of whitespace collapse to one space, and the ends are trimmed.
- Text with no words gives an empty string.
reverse_words(text: string) → string
Where you start
def reverse_words(text: str) -> str:
Worked examples
| Call | Result |
|---|---|
reverse_words("the quick brown fox") | "fox brown quick the" |
reverse_words(" a b ") | "b a" |
reverse_words("one") | "one" |
reverse_words("") | "" |
Hint
Split on whitespace, reverse the list, join with a single space.
Reference solution in Python
def reverse_words(text: str) -> str:
return ' '.join(reversed(text.split()))