Reverse Words in a String in Python: Simple, Edge-Case-Safe Solutions
Reversing the words in a sentence means flipping their order while keeping each word’s own characters intact. “Hello Python” becomes “Python Hello”. The one-liner in Python is almost too easy — but edge cases trip up a lot of candidates.
The Standard One-Liner
def reverse_words(sentence): """Reverse the order of words in a string.""" return ' '.join(sentence.split()[::-1])
print(reverse_words("Hello Python"))# Output: Python Hello
print(reverse_words("The quick brown fox"))# Output: fox brown quick Thesplit() without arguments splits on any whitespace and strips leading/trailing spaces automatically. [::-1] reverses the list. ' '.join(...) puts it back together with single spaces.
Why This Handles Multiple Spaces Correctly
# Multiple spaces between wordssentence = " Hello Python World "print(reverse_words(sentence))# Output: World Python Hello
# Contrast: split(' ') does NOT handle multiple spacesparts = sentence.split(' ')print(parts)# Output: ['', '', 'Hello', '', '', 'Python', '', '', 'World', '', '']# This produces empty strings in the reversed output — usually wrongsplit() with no arguments is the safe default. Only use split(' ') if you explicitly need to preserve spacing structure.
Step-by-Step Version for Clarity
def reverse_words_explicit(sentence): """Explicit version — easier to read and explain in an interview.""" words = sentence.split() # ['Hello', 'Python', 'World'] words.reverse() # in-place: ['World', 'Python', 'Hello'] return ' '.join(words)
print(reverse_words_explicit("Hello Python World"))# Output: World Python HelloNote that words.reverse() modifies the list in place and returns None. Do not write words = words.reverse() — that sets words to None.
Handling Empty Strings and Single Words
print(reverse_words("")) # "" — empty input, empty outputprint(reverse_words(" ")) # "" — whitespace-only, returns emptyprint(reverse_words("Python")) # "Python" — single word unchangedsplit() on an empty string or a whitespace-only string returns an empty list, so ' '.join([]) gives an empty string. No special case needed.
Reverse Characters in Each Word Too (Different Problem)
Sometimes the problem asks you to reverse every word’s characters, not just their order. That is a different task:
def reverse_each_word(sentence): """Reverse the characters within each word, keeping word order.""" return ' '.join(word[::-1] for word in sentence.split())
print(reverse_each_word("Hello Python"))# Output: olleH nohtyP
def reverse_both(sentence): """Reverse word order AND characters within each word.""" return ' '.join(word[::-1] for word in sentence.split()[::-1])
print(reverse_both("Hello Python World"))# Output: dlroW nohtyP olleHIn-Place Character-Level Reversal (No split/join)
For the constraint “no split() allowed, solve it at character level”:
def reverse_words_in_place(s): """ Reverse word order without using split(). Works on a list of characters (strings are immutable in Python). """ chars = list(s.strip())
def reverse_range(lst, i, j): while i < j: lst[i], lst[j] = lst[j], lst[i] i += 1 j -= 1
# Step 1: reverse the entire character array reverse_range(chars, 0, len(chars) - 1)
# Step 2: reverse each individual word back start = 0 for end in range(len(chars) + 1): if end == len(chars) or chars[end] == ' ': reverse_range(chars, start, end - 1) start = end + 1
return ''.join(chars)
print(reverse_words_in_place("Hello Python World"))# Output: World Python HelloThis two-step technique — reverse everything, then un-reverse each word — is a classic algorithm question. Time: O(n). Space: O(n) for the char list (O(1) if working with a mutable buffer).