Python | Reverse a string using recursion

Here we are to help you in solving the widely asked question. Lets us take a look at a recursive approach to solve this.

def rev_my_string(s):
	if len(s) == 0:
		return s
		return rev_my_string(s[1:]) + s[0]

s = input("Enter the string you want to reverse:")

print("The original string is : ", end="")

print("The reversed string(using recursion) is : ", end="")


>> Enter the string you want to reverse: We are the Master of Python - CopyAssignment

>> The original string is : We are the Master of Python - CopyAssignment

>> The reversed string(using recursion) is : tnemngissAypoC - nohtyP fo retsaM eht era eW


We accepted the input from the user and passed on that input to the function named rev_my_string. Now we computed the length of the string and if that string length turns out to be 0, then we simply return that string. Now if the string is of some length, then we call the function again and passed the sliced string to it. The string slicing is done in such a way that we access the first elements of the string and add the remaining string to the element ar zeroth index in the string. In this way, the precision continues to produce the reversed string.

We only have 1 method to solve this problem using precision. Do check out our other article wherein we have added other different methods.

Avatar of Dhvanil V

Author: Dhvanil V