Reversing Words in a String - Python Solution

Source: GeeksforGeeks

Introduction:

In this article, we will explore a Python solution to the problem of reversing the words in a given string. We will implement a class named Solution with a method called reverseWords, which takes a string S as input and returns the string with its words reversed.

Problem Statement: Given a string S containing words separated by dots, we need to reverse the order of the words in the string and return the modified string.

Example: Let's consider an example to understand the problem and its solution better.

Input: S = "Hello.World.Code"

Output: "Code.World.Hello"

Explanation:

In the given string, the words are separated by dots. The original order of the words is "Hello", "World", and "Code". After reversing the words, the modified string becomes "Code.World.Hello".

Approach: To solve this problem, we will follow a simple approach using Python's built-in string manipulation functions.

  1. Split the string: We will start by splitting the input string S using the split function with the dot character ('.') as the delimiter. This will give us a list of words.

  2. Reverse the list: Next, we will reverse the obtained list of words using Python's list-slicing technique [::-1]. This will reverse the order of the elements in the list.

  3. Join the words: Finally, we will join the reversed words using the join function with the dot character ('.') as the separator. This will give us the desired output string with the reversed words.

Implementation: Let's implement the solution in Python.

class Solution:
    # Function to reverse words in a given string.
    def reverseWords(self, S):
        # Split the string into words.
        words = S.split('.')

        # Reverse the order of words.
        reversed_words = words[::-1]

        # Join the reversed words using dot as separator.
        reversed_string = '.'.join(reversed_words)

        # Return the modified string.
        return reversed_string

Conclusion: In this article, we explored a Python solution to reverse the words in a given string. We implemented a class Solution with the method reverseWords that splits the string into words, reverses their order, and joins them back to form the modified string. This solution provides an efficient and concise way to solve the problem.

By utilizing the string manipulation functions available in Python, we can easily reverse the words in a string and achieve the desired output.

I hope you found this article informative and helpful.

Happy coding! ✨