Open In App

Python | Reverse each word in a sentence

Last Updated : 15 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Python3




# Python code to Reverse each word
# of a Sentence individually
 
# Function to Reverse words
def reverseWordSentence(Sentence):
 
    # Splitting 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))


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. 

Python3




# 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))   


Output:

skeeG rof skeeG

Approach#3: Using re.sub() function We can use re.sub() function to replace the words in sentence with reversed words in sentence. We capture the word in string with the help of group method and replace it with reversed word. 

Python3




# Python code to Reverse each word
# of a Sentence individually
import re
# Function to Reverse words
def reverseWordSentence(Sentence):
 
    # substituting reverse word in place of word in sentence
    newSentence = re.sub('(\w+)', lambda x : x.group()[::-1], Sentence)
 
    return newSentence
 
# Driver's Code
Sentence = "GeeksforGeeks is good to learn"
# Calling the reverseWordSentence
# Function to get the newSentence
print(reverseWordSentence(Sentence))


Output:

skeeGrofskeeG si doog ot nrael

Approach#4: Using map

We can split the sentence into individual words using the split() method, and then use the map() function to apply the [::-1] slice operator to each word.

Algorithm

1. Start by defining the function “reverse_words” that takes a single parameter “sentence”.
2. Split the “sentence” into individual words using the split function and store them in the variable “words”.
3. Define a lambda function that takes a string and returns its reverse. In this case, the lambda function is defined as “lambda x: x[::-1]”.
4. Apply the lambda function to each element in “words” using the map function and store the result in the variable “reversed_words”.
5. Join the elements in “reversed_words” into a single string with a space separating each element using the join function.
6. Return the resulting string

Python3




def reverse_words(sentence):
    words = sentence.split()
    reversed_words = list(map(lambda x: x[::-1], words))
    return ' '.join(reversed_words)
sentence = "GeeksforGeeks is good to learn"
print(reverse_words(sentence))


Output

skeeGrofskeeG si doog ot nrael

Time complexity: O(nm), where n is the number of words in the sentence and m is the maximum length of a word in the sentence.
Auxiliary Space: O(nm), as we are storing the reversed words in a list.



Similar Reads

Find most similar sentence in the file to the input sentence | NLP
In this article, we will find the most similar sentence in the file to the input sentence. Example: File content: "This is movie." "This is romantic movie" "This is a girl." Input: "This is a boy" Similar sentence to input: "This is a girl", "This is movie". Approach: Create a list to store all the unique words of the file.Convert all the sentences
2 min read
Python program to find the longest word in a sentence
Given a string S consisting of lowercase English alphabets, the task is to print the longest word present in the given string in python. Examples: Input: S = "be confident and be yourself"Output: "confident"Explanation:Words present in the sentence are “be”, “confident”, “and”, “be” and “yourself”. Length of each of the words are 2, 9, 3, 2, and 8
4 min read
Python - Print the last word in a sentence
Given a string, the task is to write a Python program to print the last word in that string. Examples: Input: sky is blue in color Output: color Explanation: color is last word in the sentence. Input: Learn algorithms at geeksforgeeks Output: geeksforgeeks Explanation: geeksforgeeks is last word in the sentence. Approach #1: Using For loop + String
5 min read
Word Embedding using Universal Sentence Encoder in Python
Unlike the word embedding techniques in which you represent word into vectors, in Sentence Embeddings entire sentence or text along with its semantics information is mapped into vectors of real numbers. This technique makes it possible to understand and process useful information of an entire text, which can then be used in understanding the contex
3 min read
Program to replace a word with asterisks in a sentence
For the given sentence as input, censor a specific word with asterisks ' * '. Example : Input : word = "computer" text = "GeeksforGeeks is a computer science portal for geeks. People who love computer and computer codes can contribute their valuables/ideas on computer codes/structures on here." Output : GeeksforGeeks is a ******** science portal fo
15 min read
Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word. Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a bette
2 min read
Find frequency of each word in a string in Python
Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi Aeroplane Taxi Bus" Output : frequency of Train is
7 min read
Python - Count occurrences of each word in given text file
Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the word is already present in the dictionary we increm
4 min read
Python Program to Split each word according to given percent
Given Strings with words, the task is to write a Python program to split each word into two halves on the basis of assigned percentages according to the given values. Example: Input : test_str = 'geeksforgeeks is best for all geeks and cs students', per_splt = 50Output : geeksf orgeeks i s be st f or a ll ge eks a nd c s stud ents Explanation : Eac
6 min read
Python program to capitalize the first and last character of each word in a string
Given the string, the task is to capitalize the first and last character of each word in a string. Examples: Input: hello world Output: HellO WorlDInput: welcome to geeksforgeeksOutput: WelcomE TO GeeksforgeekSApproach:1 Access the last element using indexing.Capitalize the first word using the title() method.Then join each word using join() method
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg