How do you reverse the words in a string while keeping each word's characters intact?
You split the text into words, reverse the list of words, and join them back together.
def reverse_words(text):
return " ".join(text.split()[::-1])
print(reverse_words("the sky is blue")) # blue is sky the
print(reverse_words(" hello world ")) # world hello
So how does it work? The method split with no argument cuts the text on the spaces and throws away the empty pieces, so you get a clean list of the words. The slice [::-1] reverses that list. And the method join puts the words back together with a single space between them.
There is a detail in that code that is worth knowing about. The method split with no argument also removes the spaces at the ends and squeezes the runs of spaces in the middle, so the answer has one space between the words however the input was spaced. If you had to keep the original spacing exactly, you would need a different approach.
And the complexity is O of n for the time, because you go through the text once to split it and once to join it, and O of n for the space, because the list of words and the answer are both new.
The last question in this topic does the opposite reversal.