Reverse Words in a Given String in Python
Given a string, the task is to reverse the words in it without changing the words themselves. For example, for "Learning Python is easy", the reversed string would be "easy is Python Learning" (words in reverse order).
Using split() and join()
This method splits the string into words using split(), reverses the list of words and then joins them back into a single string using join().
s = "Python is fun"
res = ' '.join(s.split()[::-1])
print(res)
Output
fun is Python
Explanation:
- s.split() splits the string into a list of words.
- [::-1] reverses the list of words.
- ' '.join(...) concatenates the reversed words into a single string separated by spaces.
Using a Loop
This method manually iterates through the list of words in reverse order, building the reversed string step by step. It is helpful when you want to control the process explicitly.
s = "Python is fun"
words = s.split()
res = ""
for word in reversed(words):
res += word + " "
res = res.strip()
print(res)
Output
fun is Python
Explanation:
- s.split() splits the string into a list of words
- reversed(words) creates an iterator to traverse the list in reverse order.
- Inside the loop, res += word + " " appends each word followed by a space.
- res.strip() removes the trailing space at the end.
Using deque from collections
A deque (double-ended queue) is efficient for large strings, as it allows O(1) pops from both ends. This method uses pop() to retrieve words in reverse order.
from collections import deque
s = "Python is fun"
words = deque(s.split())
res = ""
while words:
res += words.pop() + " "
res = res.strip()
print(res)
Output
fun is Python
Explanation:
- deque(s.split()) creates a deque for fast popping from both ends.
- words.pop() removes and returns the last word from the deque.
- res += ... appends the word followed by a space.
- res.strip() removes trailing space.
Using Stack
This method uses a stack (LIFO structure) to reverse the order of words. Words are pushed onto the stack and popped to get them in reverse order.
s = "Python is fun"
words = s.split()
stack = []
for word in words:
stack.append(word)
res = ""
while stack:
res += stack.pop() + " "
res = res.strip()
print(res)
Output
fun is Python
Explanation:
- stack.append(word) pushes each word onto the stack.
- stack.pop() removes the last word pushed, giving reversed order.