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.
Input: String to be reversed… Output: gnirtS ot eb …desrever
Algorithm and steps to follow:
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)
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.