Reverse Words
Strings: lesson 3 of 11
Flip the word order without disturbing the letters.
Lesson 3 of 11 · 4 min
Reverse Words
Step 1 of 7
split() hands back four words. From here on only whole words move — the letters inside never do.
The Idea
Reversing words is not reversing characters. Split the sentence into words, reverse that list, then join it back with single spaces.
The letters inside each word never move — only the boxes holding them swap places, which two pointers do in one pass.
Real-World Example
Name fields are exactly this problem. A form collects "Ada Byron Lovelace" and the billing system wants the parts in the opposite order. Splitting on whitespace and re-joining keeps every name intact; slicing at character level would mangle them.
The Code
def reverse_words(s):
words = s.split() # split() also eats runs of spaces
left, right = 0, len(words) - 1
while left < right: # swap the ends, then walk inward
words[left], words[right] = words[right], words[left]
left, right = left + 1, right - 1
return " ".join(words) # one clean separator
print(reverse_words("the sky is blue")) # blue is sky the
print(reverse_words(" hello world ")) # world helloYour turn
Put the steps in the right order.
- Swap the two words the pointers sit on
- Split the text on whitespace
- Join the list back with a single space
- Put one pointer at each end of the word list
Mini quiz
1 / 3