Reverse Words in a Given String in Python (original) (raw)
Last Updated : 06 Jan, 2025
In this article, we explore various ways to reverse the words in a string using Python. From simple built-in methods to advanced techniques like recursion and stacks. We are going to see various techniques to reverse a string.
Using split()
and join()
Using split() and join() is the most common method to reverse the words in a string.
Python `
Input string
s = "Geeks for Geeks"
Split the string into words, reverse the list of words, and join them back
reversed_words = ' '.join(s.split()[::-1])
print(reversed_words)
`
**Explanation:
- The
split()
method splits the string into a list of words. [::-1]
reverses the list of words.join()
combines the reversed words back into a single string.
Using a Loop
We can manually reverse the words using a loop.
Python `
s = "Geeks for Geeks"
Split the string into words
words = s.split()
Initialize an empty string to store the result
reversed_words = ""
Iterate through the words in reverse order
for word in reversed(words): reversed_words += word + " "
Strip the trailing space
reversed_words = reversed_words.strip()
print(reversed_words)
`
**Explanation:
- Split the string into words, then use a loop to traverse the words in reverse order.
- Append each word to a new string, adding a space after each word.
Using a Stack
A stack can be used to reverse the order of words.
Python `
Input string
s = "Geeks for Geeks"
Split the string into words
words = s.split()
Reverse the words using a stack
stack = [] for word in words: stack.append(word)
reversed_words = "" while stack: reversed_words += stack.pop() + " "
Strip the trailing space
reversed_words = reversed_words.strip()
Output the result
print(reversed_words)
`
**Explanation:
- Words are pushed onto a stack (a Last-In-First-Out structure).
- Popping words from the stack reverses their order.
Using Recursion
A recursive approach can also reverse the words.
Python `
s = "Geeks for Geeks"
Recursive function to reverse words
def reverse_words(words): if not words: return "" return words[-1] + " " + reverse_words(words[:-1])
Split the string and call the recursive function
reversed_words = reverse_words(s.split()).strip()
print(reversed_words)
`
**Explanation:
- The function takes the list of words, returns the last word, and recursively processes the remaining words.