Python Program to Reverse Each Word in The String / Sentence

Python Program to Reverse Each Word in The String / Sentence

Python Program to Reverse Each Word in The String / Sentence

Python interview questions and answers

In this tutorial, we are reversing each word in the string or sentence. We are not reversing the complete sentence.

This question is asked in many of the interviews. Even it is a good practice to solve it to improve your Python basics.

Example:

Input: String to be reversed…
Output: gnirtS ot eb …desrever

Algorithm and steps to follow:

  • Split each word in the string into the list using the split() method.
  • Reverse each word (each element in the list) using extended slice syntax.
  • Join all the elements in the list to form a single string using join() operation.

In the below code we are implementing all these steps in a single line of code.

" ".join([x[::-1] for x in sentence.split()])

Where, the sentence is the given string to be reversed.

Let’s write the complete code.

Python program to reverse each word in the string Python:

def reverse_each_word(sentence):
  return " ".join([x[::-1] for x in sentence.split()])


str_given = "String to be reversed..."
str_out = reverse_each_word(str_given)
print(str_out)

Output:

gnirtS ot eb …desrever

With the slight modification, we can take the string as user input instead of hard coding in the program.

Related Python Coding Questions for Practice:

This is a simple tutorial for the Python program to reverse each word in the string.

6 Comments

  1. sentence = 'Reverse Each Word in the Sentence using Python'
    l = []
    for word in sentence.split():
        l.append(word[::-1])
    print('  '.join(l))
    
  2. but if sentence having .,(,{ will create an issue
    example:-

    sent="my name is ram (ram is his first name)."
    

Leave a Reply

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