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

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!