The Wayback Machine - https://web.archive.org/web/20241127001153/https://www.geeksforgeeks.org/reverse-words-given-string-python/
Open In App

Reverse Words in a Given String in Python

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

We are given a string and we need to reverse words of a given string

Examples:

Input : str =" geeks quiz practice code"
Output : str = code practice quiz geeks  
Input : str = "my name is laxmi"
output : str= laxmi is name my 

Reverse the words in the given string program 

Python3




# Python code
# To reverse words in a given string
 
# input string
string = "geeks quiz practice code"
# reversing words in a given string
s = string.split()[::-1]
l = []
for i in s:
    # appending reversed words to l
    l.append(i)
# printing reverse words
print(" ".join(l))


Output

code practice quiz geeks

Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), where n is the length of the string

This problem has an existing solution please refer Reverse words in a given String link. We will solve this problem in python. Given below are the steps to be followed to solve this problem.

  • Separate each word in a given string using split() method of string data type in python.
  • Reverse the word separated list.
  • Print words of the list, in string form after joining each word with space using ” “.join() method in python.

Implementation:

Python3




# Function to reverse words of string
 
def rev_sentence(sentence):
 
    # first split the string into words
    words = sentence.split(' ')
 
    # then reverse the split string list and join using space
    reverse_sentence = ' '.join(reversed(words))
 
    # finally return the joined string
    return reverse_sentence
 
if __name__ == "__main__":
    input = 'geeks quiz practice code'
    print (rev_sentence(input))


Output

code practice quiz geeks

Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), where n is the length of the string

Reverse Words Using backward Iteration

This solution use the same procedure but have different methods to reverse the words in string with the help backward iteration and regular expression module. Following are the steps of our approach:

  • Find all the words in string with the help of re.findall() function. 
  • Iterate over the list in backward manner. 
  • Join the words in a string with the help of join() function.

Python3




# Function to reverse words of string
import re
def rev_sentence(sentence):
 
    # find all the words in sentence
    words = re.findall('\w+', sentence)
 
    # Backward iterate over list of words and join using space
    reverse_sentence = ' '.join(words[i] for i in range(len(words)-1, -1, -1))
 
    # finally return the joined string
    return reverse_sentence
 
if __name__ == "__main__":
    input = 'geeks quiz practice code'
    print (rev_sentence(input))


Output

code practice quiz geeks

Reverse Words Using Stack

Another approach to reverse the words in a given string is to use a stack. A stack is a data structure that supports push and pop operations. You can use a stack to reverse the words in a string by pushing the words onto the stack one by one and then popping them off the stack to form the reversed string.

Here is an example of how you can use a stack to reverse the words in a given string in Python:

Python3




# initializing string
string = "geeks quiz practice code"
 
# creating an empty stack
stack = []
 
# pushing words onto the stack
for word in string.split():
    stack.append(word)
 
# creating an empty list to store the reversed words
reversed_words = []
 
# popping words off the stack and appending them to the list
while stack:
    reversed_words.append(stack.pop())
 
# joining the reversed words with a space
reversed_string = " ".join(reversed_words)
 
# printing the reversed string
print(reversed_string)
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

code practice quiz geeks

Reverse Words Using split() python

1. The input string is split into a list of words using the split() method. By default, split() splits the string on whitespace characters (spaces, tabs, and newlines), so each word is separated into its own element of the list.

2. An empty string variable called reversed_string is initialized.

3. A for loop is used to iterate over the indices of the words list in reverse order. The loop starts from the index of the last word in the list (i.e., len(words)-1) and goes backwards to the first word (i.e., index 0). For each index, the corresponding word is appended to reversed_string, followed by a space character.

4. Finally, the extra space character at the end of reversed_string is removed using the strip() method, and the resulting string is returned.

Python3




def reverse_words(string):
    # split the string into a list of words
    words = string.split()
 
    # initialize an empty string to store the reversed words
    reversed_string = ''
 
    # loop through the words in reverse order and append them to the reversed string
    for i in range(len(words)-1, -1, -1):
        reversed_string += words[i] + ' '
 
    # remove the extra space at the end of the reversed string and return it
    return reversed_string.strip()
 
# example usage
string = "geeks quiz practice code"
reversed_string = reverse_words(string)
print(reversed_string)  # output: "code practice quiz geeks"


Output

code practice quiz geeks

time complexity: O(n)  

auxiliary space: O(n)

This approach has a time complexity of O(n) and a space complexity of O(n), where n is the length of the string.

Reverse Words in a String Using Two-Pointer Approach

Python3




# Python program for the above approach
 
# Function to reverse the words in string
def reverse_word(s, start, end):
    while start < end:
        s[start], s[end] = s[end], s[start]
        start += 1
        end -= 1
 
# Function to reverse the string
def reverse_string(s):
    s = list(s)
    start, end = 0, len(s) - 1
    reverse_word(s, start, end)
 
    start = end = 0
 
    # Iterate over the string S
    while end < len(s):
        if s[end] == ' ':
            reverse_word(s, start, end - 1)
            start = end + 1
        end += 1
 
    # Reverse the words
    reverse_word(s, start, end - 1)
    return ''.join(s)
 
 
# Driver Code
S = "geeks quiz practice code"
print(reverse_string(S))


Output

code practice quiz geeks

Time Complexity: O(N), where N is the length of the input string.

Auxiliary Space: O(1), the algorithm uses constant space to perform the reverse operation in place.



Previous Article
Next Article

Similar Reads

Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 min read
Reverse words in a given String in Java
Let's see an approach to reverse words of a given String in Java without using any of the String library function Examples: Input : "Welcome to geeksforgeeks" Output : "geeksforgeeks to Welcome" Input : "I love Java Programming" Output :"Programming Java love I" Prerequisite: Regular Expression in Java Java Code // Java Program to reverse a String
3 min read
Javascript Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples:  Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Al
4 min read
Reverse String according to the number of words
Given a string containing a number of words. If the count of words in string is even then reverse its even position's words else reverse its odd position, push reversed words at the starting of a new string and append the remaining words as it is in order. Examples: Input: Ashish Yadav Abhishek Rajput Sunil Pundir Output: ridnuP tupjaR vadaY Ashish
6 min read
Reverse the Words of a String using Stack
Given string str consisting of multiple words, the task is to reverse the entire string word by word.Examples: Input: str = "I Love To Code" Output: Code To Love IInput: str = "data structures and algorithms" Output: algorithms and structures data Approach: This problem can be solved not only with the help of the strtok() but also it can be solved
8 min read
Print words of a string in reverse order
Let there be a string say "I AM A GEEK". So, the output should be "GEEK A AM I" . This can done in many ways. One of the solutions is given in Reverse words in a string . Examples: Input : I AM A GEEK Output : GEEK A AM I Input : GfG IS THE BEST Output : BEST THE IS GfG This can be done in more simpler way by using the property of the "%s format sp
10 min read
Reverse words in a string
Given a string str, the task is to reverse the order of the words in the given string. Note that str may contain leading or trailing dots(.) or multiple trailing dots(.) between two words. The returned string should only have a single dot(.) separating the words. Examples: Input: str = "i.like.this.program.very.much" Output: str = "much.very.progra
12 min read
Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 min read
Count words that appear exactly two times in an array of words
Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There
6 min read
Reverse individual words
Given string str, we need to print the reverse of individual words. Examples: Input : Hello World Output : olleH dlroW Input : Geeks for Geeks Output : skeeG rof skeeG Method 1 (Simple): Generate all words separated by space. One by one reverse word and print them separated by space. Method 2 (Space Efficient): We use a stack to push all words befo
15+ min read
Find least start index of a substring from given String that contains all the given words in a contiguous manner
Given a string S and an array of equal length words (strings) arr[]. The task is to find the minimum start index of the substring that contains all the given words in a contiguous manner. If no such index is found, return -1.Note: The words can be in any sequence. Examples: Input: arr[ ] = {"bat", "bal", "cat"}, S = "hellocatbyebalbatcatyo"Output:
9 min read
Lexicographically largest string formed by choosing words from given Sentence as per given Pattern
Given a sentence S and a string B having distinct characters, find a string by joining the words of S according to given conditions:- Choose a word from S ifIt has at least length(B)/2 characters from string B orHaving at least one character from string B and lexicographically sorted in increasing order.The string formed should be lexicographically
7 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Check if a given string is a Reverse Bitonic String or not
Given a string str, the task is to check if that string is a Reverse Bitonic string or not. If the string str is reverse Bitonic string, then print "YES". Otherwise, print "NO". A Reverse Bitonic String is a string in which the characters are arranged in decreasing order followed by increasing order of their ASCII values. Examples: Input: str = "zy
6 min read
Reverse the substrings of the given String according to the given Array of indices
Given a string S and an array of indices A[], the task is to reverse the substrings of the given string according to the given Array of indices.Note: A[i] ? length(S), for all i.Examples: Input: S = "abcdef", A[] = {2, 5} Output: baedcf Explanation: Input: S = "abcdefghij", A[] = {2, 5} Output: baedcjihgf Approach: The idea is to use the concept of
10 min read
Number of words that can be made using exactly P consonants and Q vowels from the given string
Given a string str and two integers P and Q. The task is to find the total count of words that can be formed by choosing exactly P consonants and Q vowels from the given string.Examples: Input: str = "geek", P = 1, Q = 1 Output: 8 "ge", "ge", "eg", "ek", "eg", "ek", "ke" and "ke" are the possible words.Input: str = "crackathon", P = 4, Q = 3 Output
7 min read
Check if given words are present in a string
Given a big string and an array of small strings, all of which are smaller in length than the big string. The task is to create an array of booleans, where each boolean represents whether the small string at that index in the array of small strings is contained in the big string. Note : that you can't use language-built-in string-matching methods.
15+ min read
Program to extract words from a given String
The task is to extract words from a given string. There may be one or more space between words. Examples: Input : geeks for geeks Output : geeks for geeks Input : I love coding. Output: I love coding We have discussed a solution in the below post. How to split a string in C/C++, Python and Java? In this post, a new solution using stringstream is di
3 min read
Check if a two character string can be made using given words
Given a string of two characters and n distinct words of two characters. The task is to find if it is possible to arrange given words in such a way that the concatenated string has the given two character string as a substring. We can append a word multiple times. Examples: Input : str = "ya" words[] = {"ah", "oy", "to", "ha"} Output : YES We can j
6 min read
Count words in a given string
Given a string, count the number of words in it. The words are separated by the following characters: space (' ') or new line ('\n') or tab ('\t') or a combination of these. Recommended PracticeCount number of wordsTry It!Method 1: The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator is seen. State IN indicates t
15+ min read
Print all valid words from given dictionary that are possible using Characters of given Array
Given a dictionary of strings dict[] and a character array arr[]. Print all valid words of the dictionary that are possible using characters from the given character array.Examples: Input: dict - ["go", "bat", "me", "eat", "goal", boy", "run"] arr[] = ['e', 'o', 'b', 'a', 'm', 'g', 'l']Output: "go", "me", "goal".Explanation: Only all the characters
5 min read
Check if words in given sentence occur based on the given pattern
Given a pattern 'pattern' and a sentence 's', the task is to check if the words in the given sentence occur based on the pattern represented in the 'pattern'.Examples: Input: pattern = "abba", s = "geeks for for geeks"Output: trueExplanation: In the pattern, 'a' denotes 'geeks' and 'b' denotes 'for'. Therefore, sentence 's' follows the pattern 'pat
6 min read
Create a new string by alternately combining the characters of two halves of the string in reverse
Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. Examples: Input : s = carbohydratesOutput : hsoebtraarcdy Input : s = sunshineOutput : sennuish Explanation: Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be
7 min read
Maximize cost of repeated removal of string P or its reverse from the string S
Given two positive integers X and Y and two numeric strings S and P of length N and 2 respectively, the task is to find the maximum total cost obtained by repeatedly removing string P or the reverse of the string P from the string S at the cost of X and Y respectively. Examples: Input: S = "12333444", X = 5, Y = 4, P = "34"Output: 15Explanation:Bel
11 min read
Reverse the given string in the range [L, R]
Given a string str, and two integers L and R, the task is to reverse the string in the range [L, R] i.e. str[L...R].Examples: Input: str = "geeksforgeeks", L = 5, R = 7 Output: geeksrofgeeks Reverse the characters in the range str[5...7] = "geeksforgeeks" and the new string will be "geeksrofgeeks" Input: str = "ijklmn", L = 1, R = 2 Output: ikjlmn
4 min read
Count of Reverse Bitonic Substrings in a given String
Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string. Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns: Strictly IncreasingStrictly decreasingDecreasing and then increasing Examples: Input: S = "bade"Output: 10Explanation
8 min read
Reverse substrings of given string according to specified array indices
Given string str of length N and an array arr[] of integers, for array element arr[i](1-based indexing), reverse the substring in indices [arr[i], N - arr[i] + 1]. The task is to print the string after every reversal. Examples: Input: str = "GeeksforGeeks", arr[] = {2}Output: GkeeGrofskeesExplanation:For first element of the array is 2:Reverse the
7 min read
Find all substrings with even 1s whose reverse is also present in given String
Given a binary string str. The task is to find the size of the set(contains unique substrings) of substrings such that if there is a substring(suppose A) of length n with an even number of 1's and also there is another substring (suppose B) of the same length n and even number of 1's and it is reverse of A, then only A would be considered in the se
7 min read
Reverse given range of String for M queries
Given a string S of length N and an array of queries A[] of size M, the task is to find the final string after performing M operations on the string. In each operation reverse a segment of the string S from position (A[i] to N-A[i]+1). Examples: Input: N = 6, S = "abcdef", M = 3, A = {1, 2, 3}Output: "fbdcea"Explanation: After the first operation,
15 min read
Reverse vowels in a given string
Given a string, your task is to reverse only the vowels of string. Examples: Input : hello Output : holle Input : hello world Output : hollo werldRecommended PracticeReversing the vowelsTry It! One simple solution is to store all the vowels while scanning the string and placing the vowels in the reverse order in another iteration of string. Impleme
8 min read
Practice Tags :
three90RightbarBannerImg