Open In App

Reverse Words in a Given String in Python

Last Updated : 03 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Python 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" Rec
5 min read
Check if the given string of words can be formed from words present in the dictionary
Given a string array of M words and a dictionary of N words. The task is to check if the given string of words can be formed from words present in the dictionary. Examples: dict[] = { find, a, geeks, all, for, on, geeks, answers, inter } Input: str[] = { "find", "all", "answers", "on", "geeks", "for", "geeks" }; Output: YES all words of str[] are p
15+ min read
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
Program to reverse words in a given string in C++
Given a sentence in the form of string str, the task is to reverse each word of the given sentence in C++. Examples: Input: str = "the sky is blue" Output: blue is sky theInput: str = "I love programming" Output: programming love I Method 1: Using STL functions Reverse the given string str using STL function reverse().Iterate the reversed string an
6 min read
Reverse words in a given string | Set 2
Given string str, the task is to reverse the string by considering each word of the string, str as a single unit. Examples: Input: str = “geeks quiz practice code”Output: code practice quiz geeks Explanation: The words in the given string are [“geeks”, “quiz”, “practice”, “code”]. Therefore, after reversing the order of the words, the required outp
9 min read
C++ 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" Rec
7 min read
C 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" Rec
3 min read
Java 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" Rec
4 min read
C# 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" Rec
4 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" Rec
4 min read
Practice Tags :