Reverse Words in a Given String in Python
Last Updated :
03 Jul, 2023
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
string = "geeks quiz practice code"
s = string.split()[:: - 1 ]
l = []
for i in s:
l.append(i)
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
def rev_sentence(sentence):
words = sentence.split( ' ' )
reverse_sentence = ' ' .join( reversed (words))
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
import re
def rev_sentence(sentence):
words = re.findall( '\w+' , sentence)
reverse_sentence = ' ' .join(words[i] for i in range ( len (words) - 1 , - 1 , - 1 ))
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
string = "geeks quiz practice code"
stack = []
for word in string.split():
stack.append(word)
reversed_words = []
while stack:
reversed_words.append(stack.pop())
reversed_string = " " .join(reversed_words)
print (reversed_string)
|
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):
words = string.split()
reversed_string = ''
for i in range ( len (words) - 1 , - 1 , - 1 ):
reversed_string + = words[i] + ' '
return reversed_string.strip()
string = "geeks quiz practice code"
reversed_string = reverse_words(string)
print (reversed_string)
|
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.
Python3
def reverse_word(s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start + = 1
end - = 1
def reverse_string(s):
s = list (s)
start, end = 0 , len (s) - 1
reverse_word(s, start, end)
start = end = 0
while end < len (s):
if s[end] = = ' ' :
reverse_word(s, start, end - 1 )
start = end + 1
end + = 1
reverse_word(s, start, end - 1 )
return ''.join(s)
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.
Please Login to comment...