/  Technology   /  Reverse a string in Python using recursion

Reverse a string in Python using recursion

We can reverse a string in Python using the following methods.

  • Using for loop
  • Using slicing
  • Using reversed()
  • Using recursion

 

1. Using for loop:

In this approach we use a for loop. We first declare a function named reverse_string() and pass the given string demo_string as an argument. In the function body, we declare an empty string variable emp_str which holds the reversed string.

 

And then using the for loop, we iterate every element of demo_string, join each character in the beginning and store it in emp-str.

 

Example:

def reverse_string(demo_string):
    emp_str = ""
    for i in demo_string:
        emp_str = i + emp_str
    return emp_str

demo_string = "Python by i2tutorials"

print("The original string is: ",demo_string)
print("The reversed string is",reverse_string(demo_string))

Output:

 

2. Using slice notation:

Before learning to implement slicing for reversing a list, go through the article on slicing. 

 

In the slice notation, by omitting the start and end arguments we can print the entire list and by giving a negative number as the step value, we can print the elements from the right end till the element with index 0.

 

Example:

def reverse(demo_string):
    demo_string = demo_string[::-1]
    return demo_string

demo_string = "Python by i2tutorials"

print("The original string is: ",demo_string)
print("The original string is",reverse_string(demo_string))

Output:

 

3. Using reversed():

The reversed() method returns an iterator that iterates the given sequence in the reversed order. Once we get each character in the reverse order, we add to an empty string using the join() method. 

 

Example:

def reverse(demo_string):
    reversed_string = "".join(reversed(demo_string))
    return reversed_string

demo_string = "Python by i2tutorials"

print("The original string is: ",demo_string)
print("The reversed string is",reverse_string(demo_string))

Output:

 

4. Using recursion:

The string can also be reversed using recursion. Recursion is a process where a function calls itself.

 

Example:

def reverse(demo_string):
    if len(demo_string) == 0:
       return demo_string
    else:
       return reverse(demo-string[1:]) + str[0]

demo_string = "Python by i2tutorials"

print("The original string is: ",demo_string)
print("The reversed string is",reverse_string(demo_string))

Output:

 

Leave a comment