×

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

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Python program to find whether a given number is even or odd

Python program to find whether a given number is even or odd A number is said to be even if any number is completely divisible by 2, which means there is...

1 minute read.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Python - Binomial Distribution

Introduction Definition of the Binomial Distribution The method of counting how many instances of a specific event there have been is called the binomial distribution. It will outline the possible outcomes or...

4 minutes read.

Add a key-value pair to dictionary in Python

In programming, data type defines the type of value that a variable can hold. With help of these, we can perform various mathematical, logical, or relational operations on that particular...

5 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Operator Module In Python

Introduction The operator module is used for performing operations using methods rather than utilizing operators in Python code. The operator module provides several methods for performing the operations.  The operator module contains...

7 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Python Program for Linear Search

Introduction We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms....

4 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 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.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

Python Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.