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
Original: Python is fun to learn Words reversed: learn to fun is Python
How it works
split()turns the sentence into a list of words.insert(0, word)puts each word at the front ofreversed_words, so the last word read ends up first." ".join(reversed_words)joins the words back into a sentence with single spaces.- The letters inside each word are untouched; only the order of the words changes.
Other ways to write it
Using slicing or reversed()
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises