×

Reverse a String 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 English-like syntax that is very easy to write and understand which also reduces the maintenance cost. Python is an interpreted language which means that it uses an interpreter instead of the compiler to run the code. The interpreted language is processed at the run time thus takes less time to run. Python also has third parties modules and libraries which encourage development and modifying the code.

In this post, we are going to discuss how to reverse a string in Python. In Python, strings are ordered sequences of characters. You may not get this problem directly in an interview, but you may find its application in some other questions in which you want to reverse the string or do a similar operation. It also has some real-world applications.

String reversal is not so common, so strings do not support the inbuilt function reverse() like lists or other containers. We are going to use four approaches to reverse a string in Python, they are:

  • Slicing
  • While loop
  • Reversed() function
  • Recursion

1. Slicing

Python has an amazing feature called Slicing. With slicing, we can get a specific part of strings, tuples, and lists. Slicing can also be used to modify or delete items from mutable containers in python lists. Slicing provides very clean and short code which is easier to read.

Slicing is similar to indexing but it returns a range of elements instead of just one. The syntax of slicing is [start:stop:step]. The start and stop define the elements from where we are going to slice and till where we are slicing.  Step determines the gap between the elements.

For reversing a string in Python the code is:

Code

def reverse_str(string):   

    string = string[::-1]   

    return string   

str = input(“Enter a string:”)

print ("The string  is : ",str)   

print ("The reversed string using slicing is : ",reverse_str(str)) 

Output

Enter a string: python

The string is:python

The reversed string using slicing is:nohtyp
Reverse A String In Python

Explanation

Here we have not written anything in the start and step in the syntax of slicing which is similar to writing 0 and string length respectively. The -1 in step indicates that the interpreter has to process the string in the backward direction, henceforth reversing the string.

2. While loop

While the loop in Python is like in any other language, the statements inside the loop will run as long as the condition of the loop is true. Here, we will first take the input of the string from the user. Then we will create an empty string and store the characters in reverse order.

Code:

def reverse_str(string):   

    reversed_string=[]

length = len(string)

while length > 0:

            reversed_string += string[ length - 1 ]

            length = length - 1

returnreversed_string

str = input(“Enter a string:”)

print ("The string is: ",str)   

print ("The reversed string using While loop is: ",reverse_str(str)) 

Output

Enter a string:python

The string is:  python

The reversed string using While loop is:  nohtyp
Reverse A String In Python

Explanation

In the code above, the logic is implemented in the reverse_str function. We have initialized an empty string called reversed_string which stores the final reversed string. Then we are looping the original string in reverse order. We are storing the last element first in our reversed_string variable. After completing the iteration and appending all the characters it will return the string.

3. Reversed() function

This is a very powerful approach in which we are taking advantage of various advanced functions in Python. In this case we are using the .join() function with reversed() function. Reversed() function returns the reverse iteration of the string. The following python code demonstrates the process to reverse a string:

Code

def reverse_str(string):   

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

    return reversed_str   

str = input(“Enter a string:”)

print ("The string is: ",str)   

print ("The reversed string using Reversed function loop is: ",reverse_str(str)) 

Output

Enter a string: python

The string is:  python

The reversed string using Reversed function is:  nohtyp
Reverse A String In Python

Explanation

We have defined the function in which we are using the built-in function reversed() to traverse through all the elements in the string in reverse order. Then we are joining all the elements given by the .reversed() function by using a .join() function and storing them in a variable called reversed_str and finally, we are returning the variable.

4. Recursion

The final approach we are going to discuss in this post is recursion. Recursion is a method of solving a problem when the problem is defined in terms of itself. When a function calls itself, then it is termed a recursive function. Let us look at the code to reverse a string using recursion.

Code

def reverse_str(string):   

     if len(string) == 0: # Checking the lenght of string 

        return string   

    else:   

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

str = input(“Enter a string:”)

print ("The string is: ",str)   

print ("The reversed string using Recursion is: ",reverse_str(str)) 

Output

Enter a string: python

The string is:  python

The reversed string using Recursion is:  nohtyp
Reverse A String In Python

Explanation

In the code above, we have taken the string as an input from the user and we are passing that string to the function reverse_str which is returning us the reversed string. In the function, the logic is implemented.

We are using slicing here, but instead of just slicing one element we are taking the whole list except one element. There is a base condition defined in the function which is if the length of the string is 0, it will return the string else we will pass the string by removing the first element from it and concatenates that letter to the returned string.


Related Topics

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

How to create a login page in python

Users can access an application by providing their username and Password or by authenticating with a social media login on the login screen. Python Tkinter Python provides a variety of choices for...

3 minutes read.

Python Multithreading

In python, we can implement multithreading. In this tutorial, we will understand the basics of implementing multithreading in a python programming language. Multithreading is just like multiprocessing. We use it...

4 minutes read.

Python all() Function

Python all() Function The all() function in Python returns a Boolean value ‘True’ if all the items in iterable are true or if the iterable object is empty, else it returns False. Syntax all(iterable) Parameter Iterable: An iterable object...

1 minute read.

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Python reversed() Function

Python reversed() Function The reversed() in Python returns a reverse iterator. Syntax reversed(seq) Parameter seq: This parameter represents any iterable object. Return This function returns a reversed iterator object. Example 1 # Python Program describing # the reversed() function ...

1 minute read.

Application to get live USD/INR rate 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 Line Break

Introduction In this tutorial, you will learn line breaks in python.In Python, the new line character is used to indicate the start of a new line and the end of an...

5 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 minutes read.

How to Update Python?

How to Update Python In this article, we will discuss how we can update Python in our system. For a better understanding, this article will cover all the steps right from installation...

4 minutes read.

Python String rfind() method

The string. rfind() method in Python returns the highest index in the string if the substring sub is found else it returns -1 if the substring is not found. Syntax string.rfind(sub [,start [,end]]) Parameter sub: This parameter...

2 minutes read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

Map Syntax in Python

Introduction: In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you...

6 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.