Python Program to Reverse Each Word in The String

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.
Comments
Dwarakanath
Aniruddha Chaudhari
This is also the right solution by using for loop.