How do you reverse the words in a string while keeping each word's characters intact?
Split the string on whitespace, reverse the list of pieces, and join them back with single spaces. Python's split with no argument handles runs of whitespace and ignores leading and trailing spaces, so you do not need to strip or normalise the input yourself.
def reverse_words(text):
return " ".join(text.split()[::-1])
print(reverse_words("the sky is blue"))
print(reverse_words(" hello world "))The outputs are blue is sky the and world hello. The second call shows the whitespace handling: the extra spaces at both ends and the run of spaces in the middle are all removed, and the result uses single spaces between words.
The mechanism is that split produces a list of words, reversing that list is a constant-time pointer operation on the list, and join reassembles the string. The whole thing is linear in the length of the input, because splitting and joining each touch every character once.
The trade-off to name is that split collapses all whitespace, which changes the output when the input had meaningful spacing. If you need to preserve the original separators exactly, you have to walk the string and reverse the order of the word spans while keeping the separators where they are, which is more work. You also lose information about trailing spaces. Most interview versions of this question specify single spaces between words, and saying that you are assuming that is the right move.