Python | Reverse each word in a sentence

Given a long sentence, reverse each word of the sentence individually in the sentence itself.
Examples:

Input : Geeks For Geeks is good to learn
Output : skeeG roF skeeG si doog ot nrael

Input : Split Reverse Join
Output : tilpS esreveR nioJ

We shall use Python’s built in library function to reverse each word individually in the string itself.



Prerequisites :
1. split()
2. Reversing Techniques in Python
3. List Comprehension Method in python
4. join()

  • First split 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.

Below is the implementation of above idea.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to Reverse each word
# of a Sentence individually
  
# Function to Reverse words
def reverseWordSentence(Sentence):
  
    # Spliting the Sentence into list of words.
    words = Sentence.split(" ")
      
    # Reversing each word and creating
    # a new list of words
    # List Comprehension Technique
    newWords = [word[::-1] for word in words]
      
    # Joining the new list of words
    # to for a new Sentence
    newSentence = " ".join(newWords)
  
    return newSentence
  
# Driver's Code 
Sentence = "GeeksforGeeks is good to learn"
# Calling the reverseWordSentence 
# Function to get the newSentence
print(reverseWordSentence(Sentence))

chevron_right


Output:

skeeGrofskeeG si doog ot nrael

Python is well known for its short codes. We shall do the same task but with lesser line of codes.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to Reverse each word
# of a Sentence individually
  
# Function to Reverse words
def reverseWordSentence(Sentence):
  
    # All in One line
    return ' '.join(word[::-1] for word in Sentence.split(" "))
  
# Driver's Code 
Sentence = "Geeks for Geeks"
print(reverseWordSentence(Sentence))    

chevron_right


Output:

skeeG rof skeeG


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai



Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.