Reverse each word in a sentence in Python

This tutorial will teach you how to reverse each word in a sentence in Python. For example, if a sentence is “CodeSpeedy is great”, our output should be– “ydeepSedoC si taerg”. Let’s see how this can be done.

We are going to use these Python methods in our program to reverse each word in a given sentence.

  • split(): To split the sentence into words.
  • join(): To join the reversed words to form a new sentence.

If you are not familiar with these methods, first go through this: String split and join in Python

First, we use the split() method and break the sentence into words. These are stored in a list. We can reverse individual words in the list by using a for loop and store the new words in a new list. After all the words have been reversed, we join all the items of the new list and form a new sentence which is the required output.

Have a good look at the example code given below for reversing individual words in a sentence.

def reverse(sentence):
    #split the sentence and store the words in a list
    words = sentence.split(" ")
    #reverse each words
    reversed_words = [w[::-1] for w in words]
    #join the reversed words and form new sentence
    new_sentence = " ".join(reversed_words)
reverse("CodeSpeedy is great")

The above Python program gives the output:

ydeepSedoC si taerg

We can also write the whole reverse function in a single line. That way our code looks great and simple. Try to do it yourself.

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *