Skip to content
BytePatterns

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 hello

Python

Your turn

Put the steps in the right order.

  1. Swap the two words the pointers sit on
  2. Split the text on whitespace
  3. Join the list back with a single space
  4. Put one pointer at each end of the word list

Mini quiz

1 / 3

What does `' a b '.split()` return?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.