×

How to reverse a string in Python

In Python language, we have a few ways to reverse a string. In this article, let us discuss these ways and understand the suitability of these ways in different scenarios and needs.

There are 5 different ways to reverse a string, which are as follows:

  1. Loops
  2. Recursive functions
  3. Stack data structure
  4. Slicing
  5. reversed ()

Let’s get on to them one by one.

  • Using loops:

Program:

def reverse_string(string):

             str = ""

             for i in string:

                         str = i + str

            return str

string = input("Enter a string: ")

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

print (string)

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

print (reverse_string(string))

Output:

Enter a string: Hello

The original string is: Hello

The reversed string (using loops) is: olleH

Explanation:

In the program, we took the string input from the user to reverse it. We made a function reverse_string to write the logic. Inside the function, the string is taken as a parameter. We took another empty string str. Then, we used a loop iterating through our string and appended characters of the string to the new string. The first character is appended first then the second is appended then the third.

Table: When string to be reversed is Hello

Value of iReversed string
HH
EeH
LleH
LlleH
OolleH
  • Using recursive functions:

Program:

def reverse_string (string):

              if len (string) == 0:

                          return string

             else:

                          return reverse_string (string [1:]) + string [0]

string = input ("Enter a string: ")

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

print (string)

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

print (reverse_string (string))

Output:

Enter a string: Hello

The original string is: Hello

The reversed string (using recursion) is: olleH

Explanation:

In the program, we used a recursive function “reverse_string”. In the function, we checked the length of the string. If the length is equal to 0, that means, the string is reversed and so, we return the string to the call. If not, we slice the string to [1:] then pass it as the parameter to the function appending the first character. This continues till the whole string gets reversed.

Table:

If we take the string as: Hello

Stringstring[1:] + string[0]
Helloello + H = elloH
ellollo + e = lloeH
Llolo + l = loleH
Loo + l = olleH
  
  • Using the stack data structure

Stack is a data structure with the principle: First in last out or last in first out, which means that the element that is inserted into the stack at the last will be the first element that can be retrieved out from the stack.

Program:

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 = "Tutorials"

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

print (s)

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

print (reverse (s))

Output:

The original string is: Tutorials

The reversed string is: slairotuT

Explanation:

In the program, we used six functions:

  1. createStack () : To create the stack data structure
  2. size (stack) : For the size of the stack
  3. isEmpty (stack) : To check if the stack is empty
  4. push (stack, item) : To insert the elements into the stack
  5. pop (stack) : To retrieve the elements from the stack
  6. reverse (string) : To direct the mechanism and finally return the reversed string.

First, we defined a function called createStack in which we created an empty list with the name stack and returned it. In the second function, size, the stack is taken as the parameter and the length of the stack is found and returned. In the third function, isEmpty, stack is taken as a parameter and checked if the stack is empty or not. If the stack is empty then “True” is returned.

In the next function, push(), two parameters are taken, stack and the item to be inserted into the stack. Using the append function of lists; we append the item into the list. The next function is pop(), in which, stack is taken as a parameter, and in the body, the stack is checked if it is empty and if it is not empty, we call the pop function. This way, we delete the elements from the stack.

In the reverse function, we took the string we need to reverse as the parameter. The length of the string is found and is stored in n. Now, using the createStack function, a stack (list) is created. Now we iterated through the elements of the string and push them into the empty list. Now, we initiated a new empty string to store the reversed string. Then, we concatenated the new string with the pop () function in each iteration. Now, the reversed string is stored in the new string and is returned.

Here, the important point to be understood is that, the pop function is a recursive function and once, we call it, one after the other the characters of the string are deleted and returned, and then are appended into the new string and so the string will be reversed.

The order of insertion into the stack:

T – U – T – O – R – I – A – L - S

S
L
A
I
R
O
T
U
T

When popped out, the order will be:

S – L – A – I – R – O – T – U – T

  • Slicing

Program:

def reverse_string (string):

    string = string [ : : -1]

    return string

s = "Tutorials"

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

print (s)

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

print (reverse_string (s))

Output:

The original string is : Tutorials

The reversed string is : slairotuT

Explanation:

It is a simple predefined syntax in Python called string slicing. When we specify a string [start : stop : step], the string will be sliced or broken down from the start index to the stop – 1 index with gaps of step. In the program, we gave the step as -1 and we did not specify the start and stop indexes, which mean the whole string is sliced but with a negative step of -1 which means the string will be sliced from backwards and so it will be reversed.

  • reversed () function:

Program:

def reverse_string(string):

    string = "".join(reversed(string))

    return string

s = "Tutorials"

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

print (s)

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

print (reverse_string(s))

Output:

The original string before reversing is : Tutorials

The reversed string is : slairotuT

Explanation:

Reversed () is a predefined function in Python. It returns the reversed iterator of the specified string. These iterated characters are joined to the empty string to make it a string and so, the string will be reversed.

Above explained ways are the five different ways of reversing strings in Python programming language. These ways are used based on the situation and the feasibility in the block of code.


Related Topics

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.

Python Modules List

Python is like an ocean. If you have been working with Python, you might’ve already heard the word module. When we solve a problem in mathematics, there will be several...

3 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

To Do GUI Application using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 minutes read.