Python Program to Reverse Each Word in The String

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 step in single line of code.

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

Where, 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 simple tutorial for Python program to reverse each word in the string.

Python Interview Questions eBook

Comments

  • Dwarakanath
    September 14, 2020 at 12:47 pm
    sentence = 'Reverse Each Word in the Sentence using Python'
    l = []
    for word in sentence.split():
        l.append(word[::-1])
    print('  '.join(l))
    
    • Aniruddha Chaudhari
      September 16, 2020 at 8:39 pm

      This is also the right solution by using for loop.

Leave a Reply