Python

How to Reverse String in Python ?

By ayed_amira , on 04/25/2020 , updated on 09/10/2020 - 5 minutes to read
python-reverse-string

Overview

In this article, we will see how to reverse a python string. What can it be used for, you may ask? In programming it is not very used but it can be useful in some cases like for example to know if a word is a palindrome. A palindrome is a string of characters that can be read from left to right or right to left. In python, there is no function that allows you to do this directly as in the Java reverse method. There are several ways to reverse a string in python and I will explain them in detail in the rest of this tutorial. Let’s get started!

Reverse String Using loop

The first method is to use a for loop to allow you to browse through all the characters of a string and place them at the end of the new string. To explain, here is an example by defining the reverseLoop() function :

# Reverse a string using python loop

def reverseLoop(str):
  rev = ""
  for c in str:
      rev = c + rev
  return rev

Let’s test this function with the string “AMIRADATA” :

website = "AMIRADATA"
print(reverseLoop(website))
Output:
ATADARIMA

It works perfectly, don’t you think? 😀

Reverse String Using Recursion

In the same principle, we can use recursion to invert a string. This one will iterate on each character to add them at the beginning of the string to reverse it. Here is an example with the reverseRecursion() function:

# Reverse a string using python recursion

def reverseRecursion(str): 
    if len(str) == 0: 
        return str
    else: 
        return reverseRecursion(str[1:]) + str[0] 

Same principle as above, we will test on the string “AMIRADATA”:

print(reverseRecursion(website))
Output:
ATADARIMA

In the function we created, the string is passed as an argument to a recursive function to invert the string. The basic condition of the function is that if the length of the string is 0, the string is returned. If it is not equal to 0, the inverse function is called recursively so that the program splits the part of the string except the first character and then concatenates the first character at the end of the previously split string.

Reversing a Python String With the “[::-1]” Slicing Trick

This is the easiest way to reverse a string. In python, strings follow the sequence protocol. All these sequences support the functionality called slicing. The sequence “[::-1]” has the effect of reversing a character string.

We will encapsulate this sequence in a function to make it more obvious in the understanding. Here is an example with the reverseSlicing() function:

# Function to reverse a string using slicing
def reverseSlicing(str):
    s = str[::-1]
    return s

This results in the string “AMIRADATA”:

website = "AMIRADATA"
print(reverseSlicing(website))
Output:
ATADARIMA

the extended slice proposes to put a “step” field like [start, stop, step], and not to give any field like start and stop indicates respectively the default value at 0 and the length of the string and “-1” indicates the beginning of the end and the stop at the beginning, thus inverting the string.

Reversing a Python String Using str.join() and reversed() 

This method uses the Python iterator protocol. This method reverses a string using reverse iteration with the built-in reversed() function to go through the elements of the string in reverse order, then use the .join() function to merge all the characters resulting from the reverse iteration into a new string.

To illustrate my point, we will create a new reverseJoin() function:

# Function to reverse a string  using .join() and reversed()
def reverseJoin(string):
    string = "".join(reversed(string))
    return string

This results in the string “AMIRADATA”:

website = "AMIRADATA"
print(reverseJoin(website))
Output:
ATADARIMA

The reverse() function returns the reverse iterator of the given string, then its elements are joined empty string separated using join(). And a reverse order string is formed.

Reverse Performance Comparison

We have 4 methods to reverse a string, but which one is the fastest in execution? Here is a benchmarking of the different methods using the python library timeIt to calculate the execution time:

import timeit
s = 'amiradata' * 1000

print(timeit.repeat(lambda: reverseLoop(website)))
print(timeit.repeat(lambda: reverseRecursion(website)))
print(timeit.repeat(lambda: reverseSlicing(website)))
print(timeit.repeat(lambda: reverseJoin(website)))

What is the fastest method?

Without further ado, here are the results:

AlgorithmsExecutiin time (seconde)
reverseLoop0.66
reverseRecursion1.93
reverseSlicing0.18
reverseJoin0.44

As you can see the slicing method is the best approach if you want to optimize your code to reverse a string. This one is even 10 times faster than the recursion method which is not negligible when it comes to processing large strings.

Summary

  • reverseLoop : Uses loops to reverse the string
  • reverseRecursion : Uses recursion to reverse the string
  • reverseSlicing : Uses slicing syntax “[::-1]”  to create a reversed copy of a string
  • reverseJoin : Combines the reversed() and .join() functions to reverse the string
  • The slicing method is the fastest in terms of execution time.

Here we are at the end of this tutorial, I hope you were interested in this one. Feel free to share and enjoy this article!

You can find more articles about the python language in the python section of my website.


If you want to learn more about python, you can read this book (As an Amazon Partner, I make a profit on qualifying purchases) :


See you soon ! Or rather “! noos uoy eeS” 😀

ayed_amira

I'm a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming :)

Comments

Leave a comment

Your comment will be revised by the site if needed.