Friday, December 27, 2024
Google search engine
HomeLanguagesReverse Words in a Given String in Python

Reverse Words in a Given String in Python

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

Examples:

Input : str =" Lazyroar quiz practice code"
Output : str = code practice quiz Lazyroar  
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 = "Lazyroar 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 Lazyroar

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 = 'Lazyroar quiz practice code'
    print (rev_sentence(input))


Output

code practice quiz Lazyroar

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 = 'Lazyroar quiz practice code'
    print (rev_sentence(input))


Output

code practice quiz Lazyroar

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 = "Lazyroar 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 Lazyroar

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 = "Lazyroar quiz practice code"
reversed_string = reverse_words(string)
print(reversed_string)  # output: "code practice quiz Lazyroar"


Output

code practice quiz Lazyroar

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 = "Lazyroar quiz practice code"
print(reverse_string(S))


Output

code practice quiz Lazyroar

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.

RELATED ARTICLES

Most Popular

Recent Comments