Reverse a string using recursion in python

Learn how to String reverse in python.

String reverse in python

Introduction

When we use strings in our python code, we can come across several conditions where we have to reverse the string, but we don't have any inbuilt function for reversing the string. In that case, we can use many approaches that can be useful in reversing the string, like using extended slice syntax, looping, recursion, stack, and reversed() function.

Scope

This article meets the following points:

  • This article covers different approaches to reversing a string.
    • Using extended slice syntax
    • Using loop
    • Using recursion
    • Using stack
    • Reversing Strings With .join() and reversed()

How to Reverse a String in Python?

There can be a lot of situations while coding where you have to reverse a string to make use of it. So for that, knowing these string reversal techniques becomes necessary to make the tasks easier. We don't have any inbuilt function for reversing the string. So we follow different approaches for string reversal as listed below:

  • Reversing String using extended slice syntax
  • Reversing String using loop
  • Reversing String using recursion
  • Reversing String using stack
  • Reversing Strings With .join() and reversed()

Let's take a look at all these methods to reverse a string.

Using extended slice syntax

We can make use of python's slicing technique to reverse a string. The string can be extended sliced using the following syntax:

Where the start is the starting index by which substring is made, the end is the end index of the string, and step is the integer value that determines the increment between each integer in the string's start and end index. If the step is set to -1, it accesses the string in reverse order.

We will put starting and ending as empty to access the whole string length and the step as -1 to access the string in reverse order. Hence, we will get the whole string in reversed order. In this process, reversed version of the given string is created and assigned to our original string.

The Time Complexity of this approach is O(N)O(N) where NN is the length of the string to be reversed.

Example:

# Reverse function
def reverse(s):
    # Reversing the string using extended slicing 
    s = s[::-1]
    return s


# String to reverse
s = "String Topics"

# Printing the original string
print("Original string is :", s)

# Printing the reversed string
print("Reversed string is :", reverse(s))

Output:

Original string is : String Topics
Reversed string is : scipoT gnirtS

Using Loop

We can reverse a string by iterating the string through a reversed loop from the end of the string to the starting string and concatenating each character to a new string. In this process, the new reversed string is created and printed.

The Time Complexity of this approach is O(N)O(N) where NN is the length of the string to be reversed.

Example:

In this example, we are iterating the string in reverse order by setting the start value of the loop to len(s)−1len(s)-1. And end to -1, and step to -1 to iterate from the string length to the 0th0th index.

After iterating in reverse order, we concatenate the values to a new string variable.

# Reverse function
def reverse(s):
    string=""
    # Reversing the string using looping 
    for i in range(len(s)-1, -1, -1):
        string+=s[i]
    return string

# String to reverse
s = "String Topics"

# Printing the original string
print("Original string is :", s)

# Printing the reversed string
print("Reversed string is :", reverse(s))

Output:

Original string is : String Topics
Reversed string is : scipoT gnirtS

Using Recursion

We can use the concept of recursion to reverse the string. We will recursively call the reverse() function and keep adding the last index character to the starting of the string. Let's take an example of a string "ABC". And for that, the string is passed as an argument to the recursive function, which reverses the string. The function's base condition is that the string is returned if its length equals zero. If not equal to 0, the reverse function recursively slices the string except for the last character and concatenates the last character to the start of the string. Below is the recursion tree for the string "ABC".

Reverse a string using recursion in python

The Time Complexity of this approach is O(N)O(N) where NN is the length of the string to be reversed.

Example:

The string is passed as an argument to the recursive function in the code below, which reverses the string. The function's base condition is that the string is returned if its length equals zero. If not equal to 0, the reverse function recursively slices the string except for the last character and concatenates the last character to the start of the string. In this process, new string will not be created as we are making changes in the given string itself.


# Reverse function
def reverse(s):
    # If the length of the string is 0, return the entire string
    if(len(s)==0):
        return s
    
    # Else, slice the last index of the string and add it to the start
    else:
        return s[-1] + reverse(s[:-1])

# String to reverse
s = "Python is Awesome"

# Printing the original string
print("Original string is :", s)

# Printing the reversed string
print("Reversed string is :", reverse(s))

Output:

Original string is : Python is Awesome
Reversed string is : emosewA si nohtyP

Using Stack

We can make use of a stack to reverse our string. We will use a stack's push and pop functions to push all the characters to the stack and then pop them one by one to get the whole string in reverse order.

Below is the flowchart of an example string "ABC" reversed using stacks.

Reverse a string using recursion in python

The Time Complexity of this approach is O(N) O(N) where NN is the length of the string to be reversed.

Example:

A new stack is constructed. String characters are pushed to the stack one by one. All characters from the stack are popped and returned to the string. So in this process, the new reversed string is created and assigned to our original string.


# push function
def push(stack, elem):
    stack.append(elem)

# pop function
def pop(stack):
    if(len(stack)!=0):
        return stack.pop()
    else:
        return


# Reverse function
def reverse(s):
    n = len(s)
    stack=[]
    
    # Pushing values to stack
    for i in s:
        push(stack, i)
    
    s=''
    # popping values from stack
    for i in range(n):
        a = pop(stack)
        s+=a
    return s
    
# String to reverse
s = "String Topics"

# Printing the original string
print("Original string is :", s)

# Printing the reversed string
print("Reversed string is :", reverse(s))

Output:

Original string is : String Topics
Reversed string is : scipoT gnirtS

Reversing Strings With .join() and reversed()

reversed() function in python is used to get the reverse of the given iterator in the form of a list. .join() function concatenates all the characters of the iterator into a new original string. We can use the reversed() function to get the reverse of the string in a list and then use the .join() function to concatenate all the characters to our original string.

Time Complexity of this approach is O(N) where N is the length of the string to be reversed.

Example:

The reversed() function returns the reversed list of the provided string. And its elements are then merged using join() to form a reversed string. The old string replaces the newly reversed string by assignment operation.

def reverse(s):
    
    # Applying .join() and reversed() functions
    s = "".join(reversed(s))
    return s
    

# String to reverse
s = "Hello All, This is a Good String"

# Printing the original string
print("Original string is :", s)

# Printing the reversed string
print("Reversed string is :", reverse(s))

Output:

Original string is : Hello All, This is a Good String
Reversed string is : gnirtS dooG a si sihT ,llA olleH

Conclusion

  • We don't have any inbuilt function for reversing the string. So we follow different approaches for string reversal:
    • Reversing String using extended slice syntax
    • Reversing String using loop
    • Reversing String using recursion
    • Reversing String using stack
    • Reversing Strings With .join() and reversed()
  • All these approaches have different performances based on Time Complexity. So every approach can be beneficial based on particular needs.

How do you reverse a string in recursion in Python?

Python Program to Reverse a String Using Recursion.
def reverse(string):.
if len(string) == 0:.
return reverse(string[1:]) + string[0].
a = str(input("Enter a string: ")).
print("Reversed String: ", reverse(a)).

How do you reverse a string by recursion?

Explanation: Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way when the pointer reaches '\0', all functions accumulated in stack print char at passed location (str) and return one by one.

Is there a reverse string function in Python?

There is no built-in function to reverse a String in Python. The fastest (and easiest?) way is to use a slice that steps backwards, -1 .

Does Reverse () work on strings?

These features allow you to use slicing to directly generate a copy of a given string in reverse order. The second option is to use the built-in function reversed() to create an iterator that yields the characters of an input string in reverse order. ... Reversing Strings Through Slicing..