Python programs / Strings / Reverse words in a string

Python Program to Reverse Words in a String

Beginner Strings

Reverses the order of the words in a sentence, keeping each word spelt forwards, with split(), list slicing and join().

Reversing the words of a sentence turns "Python is fun to learn" into "learn to fun is Python": the words swap places, but each one is still spelt forwards. That's different from reversing the whole string, which gives "nrael ot nuf si nohtyP".

Program

def reverse_words(sentence):
    """The sentence with its words in reverse order."""
    words = sentence.split()
    return " ".join(words[::-1])


sentence = "Python is fun to learn"
print("Original:", sentence)
print("Reversed:", reverse_words(sentence))

Open in the editor Download reverse_words.py

Output

Original: Python is fun to learn
Reversed: learn to fun is Python

How it works

  1. split() breaks the sentence into a list of words at the spaces: ['Python', 'is', 'fun', 'to', 'learn']. With nothing in its brackets, it treats any run of spaces as one break, so extra spaces don't make empty words.
  2. words[::-1] is the list backwards (lists), and " ".join() glues the words into one string with a space between each pair (string methods).
  3. The program prints the sentence, then the sentence with its words reversed.
Step Result
sentence.split() ['Python', 'is', 'fun', 'to', 'learn']
words[::-1] ['learn', 'to', 'fun', 'is', 'Python']
" ".join(words[::-1]) 'learn to fun is Python'

Other ways to write it

With reversed()

reversed() goes through the list from the end without making a reversed copy, and join() accepts it as it is.

def reverse_words(sentence):
    return " ".join(reversed(sentence.split()))

print(reverse_words("one two three"))

With a loop

Some courses ask for it without slicing or reversed(). Each word goes in front of the words before it, so the last word ends up first. strip() then removes the space left at the end.

def reverse_words(sentence):
    result = ""
    for word in sentence.split():
        result = word + " " + result
    return result.strip()

print(reverse_words("one two three"))

Try it yourself

  • Reverse "Hello, world!": the punctuation stays with its word, giving "world! Hello,".
  • Reverse each word but keep their order, so "Python is fun" becomes "nohtyP si nuf": use word[::-1] on each one.
  • Put two spaces between two of the words. split() ignores the extra space, but split(" ") doesn't: try both.
  • Reverse the order of the words and each word as well, and compare the result with sentence[::-1].

More strings programs

Share this program