×

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

How to Configure Python Interpreter in Eclipse

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.

Defaultdict in Python

In this tutorial, we will study What is defaultdict in Python We will understand it with the aid of certain examples. Before this, we will have a look at dictionaries...

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.

Python Bitwise Operators

When used with variables and objects in an expression, operators are tokens that carry out calculations. The variables and items to which the computation is applied are known as operands....

5 minutes read.

Python String istittle() method

Python String istittle() method The string.istittle() method returns a boolean value true if the string is a titlecased string and there is at least one character, for example uppercase characters may...

2 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

Python input() function

Python input() function The input() function in Python reads a line from input and converts it to a string (stripping a trailing newline). Syntax input([prompt]) Parameter prompt: This function represents a string, depicting a default...

1 minute read.

Python vs R

Python: - Python is a popular high-level, general-purpose programming language. Python (the most recent version is Python 3) is a programming language used in the software industry for website development, machine...

3 minutes read.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

Python abs() function

Python abs() function The abs() function returns the absolute value of a number. Syntax abs(x) Parameter x: The parameter ‘x’ can be an integer value, a floating point number or a complex number. Return This function returns...

1 minute read.

Python tuple() function

Python tuple() function The tuple() function in Python creates a tuple object. Syntax tuple([iterable]) Parameter Iterable: This parameter represents a sequence, collection or an iterator object. Return This function returns a tuple object. Example 1 # Python Program explaining #...

1 minute read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

API Requests using Python

What is an API? API stands for Application Programming Interface. It is commonly known as API. It provides an environment that helps two or more computer programs to contact each other....

5 minutes read.

How to Download all Modules 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.