31: Python Program to reverse a String


Question 31) Write a Python Program to reverse a String.


Solution 1: Using Slicing

input_string = "Environment"

reversed_string = input_string[::-1]

print(reversed_string)
Output:

tnemnorivnE


Solution 2: Using for loop

input_string = "Python"
reversed_string = ""

for char in input_string:
    reversed_string = char + reversed_string

print(reversed_string)
Output:

nohtyP


Solution 3: Using recurssion function

def recursion_reverse_string(input_str):
    if len(input_str) == 0:
        return input_str
    else:
        return reverse_string(input_str[1:]) + input_str[0]

reversed_string = recursion_reverse_string("Hello")
print(reversed_string)
Output:

olleH

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap