Editor

Python Program to Reverse the Words in a Sentence

Beginner · Strings

This program reverses the order of the words in a sentence while keeping each word spelled normally, so "Python is fun" becomes "fun is Python". It is different from reversing a string, which would turn the letters round too.

Program

reverse_words.py
sentence = "Python is fun to learn" # or: sentence = input("Enter a sentence: ")
words = sentence.split()
reversed_words = []
for word in words:
reversed_words.insert(0, word) # put each word at the front
result = " ".join(reversed_words)
print("Original: ", sentence)
print("Words reversed:", result)
Output
Original:       Python is fun to learn
Words reversed: learn to fun is Python

How it works

  1. split() turns the sentence into a list of words.
  2. insert(0, word) puts each word at the front of reversed_words, so the last word read ends up first.
  3. " ".join(reversed_words) joins the words back into a sentence with single spaces.
  4. The letters inside each word are untouched; only the order of the words changes.

Other ways to write it

Using slicing or reversed()

Using slicing or reversed()
sentence = "Python is fun to learn"
print("With [::-1]: ", " ".join(sentence.split()[::-1]))
print("With reversed():", " ".join(reversed(sentence.split())))
Output
With [::-1]:    learn to fun is Python
With reversed(): learn to fun is Python

[::-1] gives the list of words backwards, and reversed() walks the list from the end without making a copy. Either is the usual way to write this in real code.

Reverse each word but keep the order

Reverse each word but keep the order
sentence = "Python is fun to learn"
result = []
for word in sentence.split():
result.append(word[::-1])
print("Each word reversed:", " ".join(result))
Output
Each word reversed: nohtyP si nuf ot nrael

Here word[::-1] reverses the letters of each word, but the words stay in their places, which is another common exam question.

Try it yourself

Reverse the words of "Practice makes a man perfect" and check the output by hand.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises