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 (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

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