Write A Python Function To Reverse A String If Its Length Is A Multiple Of 4

Python program is provided with a string containing a word,  your task is to write a Python  function to check if the string is having a length of multiples of 4 if so reverse the string else keep it as is.

let's ask a user to enter the string and use the Python function to to perform the above task

 

Write A Python Function To Reverse A String If Its Length Is A Multiple Of 4

 



Write A Python Function To Reverse A String If Its Length Is A Multiple Of 4

Let's define a function named reverse4() and pass string variable text as an input argument to the Python function.  In the function body Check if the string  length is multiples of 4 if so return the reverse string else return the original string.  


Using the if statement check if the length of the string is multiples of 4 by performing the string length by modulus of 4 and check if reminder is zero. Also to reverse a string we will be using the string slicing  method using [::-1].  this will reverse a string

def reverse4(text):
   if len(text) % 4 == 0:
       return text[::-1]
   return text




In the main program, take a variable data to store the string,  ask a user to enter a string using the input function call  and store it in the data variable. Once the user enters a string call the function reverse4() by passing the input string argument as data to it and once the function gets executed store the new string as a return value into the new_string variable

finally print the new string using the print function call.

data = input("Enter a String : ")
new_string = reverse4(data)
print("New String is : ", new_string)




Code
==============

def reverse4(text):
   if len(text) % 4 == 0:
       return text[::-1]
   return text


data = input("Enter a String : ")
new_string = reverse4(data)
print("New String is : ", new_string)





Output
============
Enter a String : help
New String is :  pleh




OUTPUT
===========
Enter a String : Write A Python Function To Reverse A String If Its Length Is A Multiple Of 4
New String is :  4 fO elpitluM A sI htgneL stI fI gnirtS A esreveR oT noitcnuF nohtyP A etirW




Output
============
Enter a String : hello
New String is :  hello




Conclusion
===============
Execute the above program by Providing the input string having the length of multiple of 4 and  non multiples of 4  spring length, note down the results.

Comment down below if you have any suggestions to improve the program






Post a Comment

0 Comments