Python program to reverse each word in a sentence?
Answers
Prerequisites :
1. split()
2. Reversing Techniques in Python
3. List Comprehension Method in python
4. join()
First split the the sentence into list of words.
Reverse each word of the string in the list individually.
Join the words in the list to form a new sentence.
To work out any problem in python, we will need to take input first and it is the same process on this question too.
Taking the input gives us the sentence in one whole sentence. Words will not be taken separately.
sentence = input().
And now, we will need to take each word in the sentence and reverse it by REPLACING it.
The replace function in python : replace(x,y)
x is the word you want to replace and y in the what you want to replace x with.
To check for every word, I will be using the for loop and we need to split it. Without the split, the code wouldn't work.
for word in sentence,split():
This is the part where the replace function kicks in.
for word in sentence:
sentence = sentence.replace(word,word[::-1])
The word[::-1] reverses the string.
Now, all that's left is to print the new string.
And we have to do:
print(sentence)
And there we go! That is your code. So simple, isn't it?
Here is the final code:
sentence = input()
for word in sentence.split():
sentence = sentence.replace(word,word[::-1])
print(sentence)
The outputs are exactly right. Checked it twice! :)
for word in sentence.spli()
print(word[-1::-1])
3 lines ;)