The Wayback Machine - https://web.archive.org/web/20241001034520/https://www.geeksforgeeks.org/python-reverse-word-sentence/
Open In App

Python | Reverse each word in a sentence

Last Updated : 15 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
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
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
Pandas - Convert the first and last character of each word to upper case in a series
In python, if we wish to convert only the first character of every word to uppercase, we can use the capitalize() method. Or we can take just the first character of the string and change it to uppercase using the upper() method. So, to convert the first and last character of each word to upper case in a series we will be using a similar approach. F
2 min read
Calculate the number of characters in each word in a Pandas series
To calculate the numbers of characters we use Series.str.len(). This function returns the count of the characters in each word in a series. Syntax: Series.str.len() Return type: Series of integer values. NULL values might be present too depending upon caller series. Another way to find the number of characters by using len() function (that wrapped
2 min read
Python IMDbPY – Get each episode name of each season of the series
In this article we will see how we can get the name/title of each episode for each season of the series from the episodes info set. Each series have seasons and each season has multiple episodes i.e episode is the subset of season and season is the subset of series. We get the episodes by adding episodes info set to the series In order to get this
3 min read
Python IMDbPY – Getting each episode year of each season of the series
In this article we will see how we can get the year of each episode for each season of the series from the episodes info set. Each series have seasons and each season has multiple episodes i.e episode is the subset of season and season is the subset of series. We get the episodes details by adding episodes info set to the series In order to get thi
3 min read
Python IMDbPY – Get each episode ID of each season of the series
In this article we will see how we can get the id of each episode for each season of the series from the episodes info set. Each series have seasons and each season has multiple episodes i.e episode is the subset of season and season is the subset of series. We get the episodes details by adding episodes info set to the series In order to get this
2 min read
Python | Remove all duplicates words from a given sentence
Given a sentence containing n words/strings. Remove all duplicates words/strings which are similar to each others. Examples: Input : Geeks for Geeks Output : Geeks for Input : Python is great and Java is also great Output : is also Java Python and great We can solve this problem quickly using python Counter() method. Approach is very simple. 1) Spl
7 min read
Python | Sort words of sentence in ascending order
Given a sentence, sort it alphabetically in ascending order. Examples: Input : to learn programming refer geeksforgeeksOutput : geeksforgeeks learn programming refer to Input : geeks for geeksOutput : for geeks geeks Approach 1 : We will use the built-in library function to sort the words of the sentence in ascending order. Prerequisites: split() s
2 min read
Python | Perform Sentence Segmentation Using Spacy
The process of deciding from where the sentences actually start or end in NLP or we can simply say that here we are dividing a paragraph based on sentences. This process is known as Sentence Segmentation. In Python, we implement this part of NLP using the spacy library. Spacy is used for Natural Language Processing in Python. To use this library in
2 min read
Python | Word Similarity using spaCy
Word similarity is a number between 0 to 1 which tells us how close two words are, semantically. This is done by finding similarity between word vectors in the vector space. spaCy, one of the fastest NLP libraries widely used today, provides a simple method for this task. spaCy's Model - spaCy supports two methods to find word similarity: using con
2 min read
Second most repeated word in a sequence in Python
Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. (Considering no two words are the second most repeated, there will be always a single word). Examples: Input : {"aaa", "bbb", "ccc", "bbb", "aaa", "aaa"} Output : bbb Input : {"geeks", "for", "geeks", "for", "geeks", "aaa"} Outp
4 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read
Generating Word Cloud in Python
Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites. For generating word cloud in Python, modules needed are
2 min read
Generating Word Cloud in Python | Set 2
Prerequisite: Generating Word Cloud in Python | Set - 1Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites.F
5 min read
Python | TextBlob.Word.spellcheck() method
With the help of TextBlob.Word.spellcheck() method, we can check the word if that word have spelling mistake by using TextBlob.Word.spellcheck() method. Syntax : TextBlob.Word.spellcheck() Return : Return the word with correctness accuracy. Example #1 : In this example we can say that by using TextBlob.Word.spellcheck() method, we are able to get t
1 min read
Converting WhatsApp chat data into a Word Cloud using Python
Let us see how to create a word cloud using a WhatsApp chat file. Convert the WhatsApp chat file from .txt format to .csv file. This can be done using Pandas. Create a DataFrame which read the .txt file. The .txt file had no columns like it is in an .csv file. Then, split the data into columns by separating them and giving each column a name. The f
4 min read
Python - Separate first word from String
Sometimes, while working with Python strings, we can have a problem in which we need to separate the first word from the entire string. This can have possible applications in many domains such as day-day and web-development. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is the brute force way in which t
7 min read
How to obtain the line number in which given word is present using Python?
To obtain the line number from the file where the given word is present, create a list in which each index contains the content of each line with Python. To do so follow the below instruction. Get Line Number of Certain Phrase in a Text fileBelow are the methods that we will cover in this article. Using IterationUsing EnumerateInput file: File1.txt
3 min read
How to replace a word in excel using Python?
Excel is a very useful tool where we can have the data in the format of rows and columns. We can say that before the database comes into existence, excel played an important role in the storage of data. Nowadays using Excel input, many batch processing is getting done. There may be the requirement of replacing text in Excel sheet is always there as
3 min read
Speak the meaning of the word using Python
The following article shows how by the use of two modules named, pyttsx3 and PyDictionary, we can make our system say out the meaning of the word given as input. It is module which speak the meaning when we want to have the meaning of the particular word. Modules neededPyDictionary: It is a Dictionary Module for Python 2-3 to get meanings, translat
2 min read
Pulling a random word or string from a line in a text file in Python
File handling in Python is really simple and easy to implement. In order to pull a random word or string from a text file, we will first open the file in read mode and then use the methods in Python's random module to pick a random word. There are various ways to perform this operation: This is the text file we will read from: Method 1: Using rando
2 min read
Generate Word Clouds Of Any Shape In Python
In this article, we will discuss how to create word clouds of any shape in Python. The term WordCloud refers to a data visualization technique for showing text data in which the size of each word indicates its frequency or relevance. To create a word cloud of any shape, use Python's Matplotlib, word cloud, NumPy, and PIL packages. Stepwise Implemen
6 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. The problem in hand could be
4 min read
Find the Frequency of a Particular Word in a Cell in an Excel Table in Python
In this article, we'll look at how to use Python to find the number of times a word appears in a cell of an Excel file. Before we begin with the steps of the solution, the following modules/libraries must be installed. We will use the following sample Excel file to determine the frequency of the input words. Dataset Used It can be downloaded from h
5 min read
How to create Word Art from an image using Python?
In this article, we are going to learn how to create word art from an image using Python. In this, we are going to take an image as input and then created a similar image in a text form using the characters. We can perform this task with the help of pillow and pywhatkit modules of Python. Pillow This library offers a wide range of file format compa
2 min read
Python Capitalize First Letter of Every Word in String
In text manipulation in Python, capitalizing the first letter of every word in a string is a common and essential task. This operation enhances the visual presentation of text and is particularly useful when dealing with user input, titles, or any scenario where proper capitalization is desired. In this article, we will explore some approaches to c
3 min read
Python Slicing | Reverse an array in groups of given size
Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] k = 3 Output: [3, 2, 1, 6, 5, 4, 9, 8, 7] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 Output: [5, 4, 3, 2, 1, 8, 7, 6] Input: arr = [1, 2, 3, 4, 5, 6] k = 1 Output: [1, 2, 3, 4, 5, 6] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k =
5 min read
Reverse bits of a positive integer number in Python
Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this problem quickly in Python. Approach is very simple,
4 min read
Article Tags :
Practice Tags :