Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Python Program to Reverse a String

Last Updated on May 17, 2023 by Prepbytes

There are a number of situations when using strings in Python programming when we need to reverse the string, but there isn’t a built-in function for doing so. If so, there are a variety of methods we can employ to reverse the string, including the expanded slice syntax, looping, recursion, stacking, and reversed() functions. We will write a Python program to reverse a string with multiple methods in this blog.

Example:

Input: prepbytes
Output: setybperp

How to Reverse a String in Python?

Many times when programming, you may need to reverse a string in order to use it. To make the jobs easier, it is therefore vital to be familiar with certain string reversal techniques. No built-in function exists to reverse the string. As a result, we employ the several methods for string reversal outlined below:

METHOD 1: Reverse a String in Python by Using a Loop

Using a Python loop, we will reverse a string. To begin, just initialize an empty string called str and execute a for loop from the string’s beginning point to its endpoint. The character that the current pointer is pointing at should be added before the str inside the for loop.

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: Reverse a String in Python by Using a Recursion

The original string is supplied as a parameter to a recursive function that reverses the string. The function’s default assumption is that a string will be returned if its length equals zero. Recursively calling the reverse function will slice the string, except for the first section, and concatenate the first character to the end of the sliced string if the length of the string is not equal to zero.

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: Reverse a String in Python by Using a Stack

The stack is left empty. Each character in the string is pushed to the stack one at a time. Each character from the stack is individually removed and added back to the string. The reversed string will be the outcome.

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: Reverse a String in Python by Using an Extended Slice

Extended slices allow you to add a "step" field as [start, stop, step]. If you omit a start or stop field, the default values are 0 and the length of the string, respectively. A "-1" indicates that you want to start at the end and stop at the beginning, which would reverse the direction of the text.

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: Reverse a String in Python by Using reversed() Method

The items of the iterator returned by the reversed() function are then combined into an empty string by the join() function. And a series of orders is created in reverse.

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: Reverse a String in Python by Using List Comprehension

List comprehension produces a list of a string’s elements in reverse order, and then uses join() to connect those elements. And a series of orders are created in reverse.

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: Reverse a String in Python by Using the Function Call

A function that reverses a string by first converting it to a list, then back to a 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
We’ve covered a variety of algorithms to reverse a string in Python in this blog. There are numerous ways to reverse a string, and by mastering all of them, you can master a programming language like Python. Don’t stop there; continue to practice questions to realize your goals.

FAQ related to Reverse a String in Python

Q1. Can I reverse a string in place in Python?
Ans. No, strings in Python are immutable, which means that their values cannot be changed once they are created. Therefore, it is not possible to reverse a string in place in Python.

Q2. How can I reverse a string using string slicing in Python?
Ans. To reverse a string using string slicing in Python, you can use the following code: string_name[::-1]. The [::-1] part of the code creates a new string that contains all the characters of the original string in reverse order.

Q3. What does it mean to reverse a string in Python?
Ans. Reversing a string in Python means to create a new string that contains the characters of the original string in reverse order.

Q4. What are some ways to reverse a string in Python?
Ans. There are several ways to reverse a string in Python, including using string slicing, the reverse() method, or using a loop to iterate through the string and build a new reversed string.

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 *