A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/reverse-words-given-string-python/ below:

Reverse Words in a Given String in Python

Reverse Words in a Given String in Python

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:

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:

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:

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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4