Python Program to Reverse a String

In this blog, we will see different approaches to write a python program to reverse a string. Python doesn’t have an inbuilt reverse method to reverse the string, but by performing some tricks we can reverse a string in python.

Example:

Input: prepbytes
Output: setybperp

How to Reverse a String in Python

There are various ways to write a python program to reverse a string:-

METHOD 1 (By Using a Loop):

We will reverse a string by using a loop in python. Firstly, just initialize an empty string str and run a for loop from the initial point of the string to the ending point of the string. Inside the for loop add the character which the current pointer is pointing in front of the str.

Code Implementation

def reverse(s):
    str = ""
    for i in s:
        str = i + str
    return str

s = "PrepBytes"

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

print("The reversed string After using loops is : ", end="")
print(reverse(s))

Output

The original string is : PrepBytes
The reversed string After using loops is : setyBperP

Time Complexity: O(n) will be the time complexity for reversing a string in python.

Space Complexity: O(1) will be the space complexity for reversing a string in python using a loop.

METHOD 2 (By Using a Recursion):

A recursive function is used to reverse the string in which the original string is passed as the parameter. In the function, base condition is that if the length of the string is equal to 0, the string is returned. If length of the string is not equal to zero, then the reverse function will be recursively called to slice the part expect the first part of the string and concatenate the first character to the end of the sliced string.

Code Implementation

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


s = "PrepBytes"

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

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

Output

The original string is : PrepBytes
The reversed string(using recursion) is : setyBperP

Time Complexity: O(n) will be the time complexity for coding the python program to reverse a string using recursion.

Space Complexity: O(n) will be the space complexity for coding the python program to reverse a string using recursion.

METHOD 3 (By Using a Stack):

An empty stack is created. One by one the character of the string is pushed to the stack. One by one all characters from the stack are popped and put back to a string. The resultant string will be the reversed string.

Code Implementation

def createStack():
    stack = []
    return stack

def size(stack):
    return len(stack)

def isEmpty(stack):
    if size(stack) == 0:
        return true

def push(stack, item):
    stack.append(item)

def pop(stack):
    if isEmpty(stack):
        return
    return stack.pop()

def reverse(string):
    n = len(string)

    stack = createStack()

    for i in range(0, n, 1):
        push(stack, string[i])

    string = ""
    for i in range(0, n, 1):
        string += pop(stack)

    return string


s = "PrepBytes"
print("The original string is : ", end="")
print(s)
print("The reversed string using stack is : ", end="")
print(reverse(s))

Output

The original string is : PrepBytes
The reversed string using stack is : setyBperP

Time Complexity: O(n) will be the time complexity for a python program to reverse a string.

Space Complexity: O(n) will be the time complexity for a python program to reverse a string.

METHOD 4 (By Using an Extended Slice):

Extended slice offers to put a “step” field as [start, stop, step], and giving no field as start and stop indicates default to 0 and string length respectively, and “-1” denotes starting from the end and stop at the start, hence reversing a string.

Code Implementation

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

s = "PrepBytes"

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

print("The reversed string using extended slice syntax is : ", end="")
print(reverse(s))

Output

The original string is : PrepBytes
The reversed string using extended slice syntax is : setyBperP

Time complexity: O(n) will be the time complexity for a python program to reverse a string using an extended slice.

Auxiliary Space: O(1) will be the space complexity for a python program to reverse a string using an extended slice

METHOD 5 (By Using reversed() method):

The reversed() returns the reversed iterator of the given string and then its elements are joined to an empty string separated using join(). And a reversed order string is formed.

Code Implementation

def reverse(string):
    string = "".join(reversed(string))
    return string

s = "PrepBytes"

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

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

Output

The original string is : PrepBytes
The reversed string using reversed is : setyBperP

Time Complexity: O(n)
Space Complexity: O(1)

METHOD 6 (By Using list comprehension):

List comprehension creates the list of elements of a string in reverse order and then its elements are joined using join(). And a reversed order string is formed.

Code Implementation

def reverse(string):
    string = [string[i] for i in range(len(string)-1, -1, -1)]
    return "".join(string)

s = "PrepBytes"

print("The original string is : ", s)

print("The reversed string using reversed is : ", reverse(s))

Output

The original string is :  PrepBytes
The reversed string using reversed is :  setyBperP

Time complexity: O(n)
Space complexity: O(1)

METHOD 7 (By Using the function call):

Function to reverse a string by converting string to list then reversed it and again convert it to string.

Code Implementation

def reverse(string):
    string = list(string)
    string.reverse()
    return "".join(string)

s = "PrepBytes"

print("The original string is : ", s)

print("The reversed string is : ", reverse(s))

Output

The original string is :  PrepBytes
The reversed string is :  setyBperP

Time complexity: O(n)
Space complexity: O(1)

Conclusion
In this blog, we have discussed various approaches to write python program to reverse a string. Reversing a string is possible in many ways, and by practicing all the types, you can conquer the coding language like python. Don’t stop here, practice more questions to achieve your dreams.

Other Python Programs
Python program to reverse a number
Python program for heap sort
Python program to check armstrong number
Python program to check leap year
Python program to convert celsius to fahrenheit
Python program to find factorial of a number
Python program to reverse a linked list
Python Program to find the middle of a linked list using only one traversal
Python Program to Add Two Numbers
Python Program to Check Palindrome Number
Python Program to Print the Fibonacci Series
Python Loop Program
Anagram Program in Python
Fizzbuzz Program in Python
String Programs in Python
List Program in Python
Prime Number Program in Python
Exception Handling in Python

Leave a Reply

Your email address will not be published. Required fields are marked *