×

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 Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

Python Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Python logging Module

Python logging Module Introduction By logging word we understand the tracking of the events which happens when we run some software. Logging process is very important part for developing software, debugging...

12 minutes read.

Python Arithmetic Operators

An arithmetic operator is a mathematical operator that is used to operate on two operands. Based on the operator used, action is performed on the operands, and output is delivered. Following...

3 minutes read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

What is Ipython shell?

IPython is a command shell for computing in multiple programming languages. IPython was developed for python language by Fernando Perez in 2001 as a well-equipped python interpreter that offers shell...

3 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python id() function

Python id() function The id() function in Python returns an id for the specified object where all the objects in has its own unique id. Syntax id(object) Parameter object: This parameter represents any object, String, Number, List,...

1 minute read.

Python e-book free download

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. There are many sources to learn python. In this...

3 minutes read.

Import py file in Python

In Python programming language, a module is a single layer of block of Python code that can be loaded and used by importing into other Python block of code. A module...

4 minutes read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Python Prime factorization

Python Prime factorization In this tutorial, we will design a program where we will find all the prime factors of a number. Then, we will print all these prime factors of...

3 minutes read.