Write a Python Class to Reverse a String Word by Word

Hi in this article you will learn how to define a Python class to reverse a given string word by word.  Let's try to solve this using the below Python program.

I will be defining individual functions to get the  input string,  reverse the string and display the string to standard output.

 


Write a Python Class to Reverse a String Word by Word




Write a Python Class to Reverse a String Word by Word

Let's take a class named reverse and define a  default constructor by taking to variables text and result,  text variable is used for input string and result variable will be used for output string.

class reverse:

   def __init__(self):
       self.text = ""
       self.result = ""



Inside the Python class define another function named as get in order to get a string from the user as shown below.

   def get(self):
       self.text = input("Enter a String : ")



Inside the Python class define a function named as execute and iterate all the words present in the input string using the split function call and then reverse the each word and then append it  to the result string later display on to the standard output

   def execute(self):
       for word in self.text.split():
           self.result += word[::-1] + " "




Inside the Python class define a function to display the rivers of a string statement to display the result string

   def display(self):
       print(f"The reverse of string is : {self.result}")




Now in the main program take a string object and call the  be fault constructor of the class and instantiate the class. Use the gate execute and display function calls to  get the string input then reverse it word by word and then display it on to the standard output.

string_obj = reverse()
string_obj.get()
string_obj.execute()
string_obj.display()





Complete Python Program
===============================


class reverse:

def __init__(self):
self.text = ""
self.result = ""

def get(self):
self.text = input("Enter a String : ")

def execute(self):
for word in self.text.split():
self.result += word[::-1] + " "

def display(self):
print(f"The reverse of string is : {self.result}")


string_obj = reverse()
string_obj.get()
string_obj.execute()
string_obj.display()



 

Output 1
======================

Enter a String : hello are you there
The reverse of string is : olleh era uoy ereht


 

 

Output 2
======================

Enter a String : Write a Python Class to Reverse a String Word by Word
The reverse of string is : etirW a nohtyP ssalC ot esreveR a gnirtS droW yb droW 




Conclusion
===============

Execute the above Python program  by providing random string values as an input to the python script and note down the reverse of a string world by word.

Commented down  below if you have any queries regarding the above python.


Post a Comment

0 Comments