Python Reverse String Examples [5+ Methods]


Written by - Bashir Alam
Reviewed by - Deepak Prasad

Introduction to python reverse string

Python strings are the collection of Unicode characters. Everything that is written inside single, double, or triple quotation marks will be considered as strings in python. Python has numerous functions for string manipulation, but it does not have built-in functions for reversing strings. But that does not mean we cannot reverse a string in python. There are various methods to reverse a string in python and some of which we will discuss in this tutorial. By the end of this tutorial, you will have a strong command over python string reverse and you will be familiar with multiple ways.

 

Python reverse string using slicing technique

In python strings follow the sequence protocol. Like all other sequences, strings support an interesting feature called slicing. We can view slicing as an extension of the square brackets indexing syntax. The slicing starts with the starting position index and ending position index. The step parameter is used to specify the steps to take from the start to end index. All these parameters are optional. By default the starting index value is 0. Python string slicing always follows this rule:

String[: i] + string[i : ] == string for any index i.

The interesting part of slicing is that we can produce a reverse of the string. The following syntax of slicing produce the reverse of string:

String_name[::-1]

Because python strings are sequences this is a quick and easy way to get a reversed copy of a string.  Let us take an example of a string and reverse it using the slicing technique.

# string
string = "Tajikistan"

# printing the reverse
print(string[::-1])

Output:

natsikijaT

Now let us create a function which reverses a python string and returns the reversed one. See the example below:

# reverse function
def reverseFunction(string):

   # return reverse
   return string[::-1]

# calling a function
print(reverseFunction("This is me"))

Output:

em si sihT

We can also reverse the list of strings using the same method. See the following example of a reverse list containing string value.

# reverse function
def reverseFunction(string):

   # return reverse
   return string[::-1]

# calling a function
print(reverseFunction(["a", "b", "c", "d"]))

Output:

['d', 'c', 'b', 'a']

 

Python reverse string using reversed and join methods

In python, there is a built-in function known as reversed() which returns a reversed iterator from the specified sequence argument. See the example below which uses the reversed method.

# string
string = "bashir"

# printing
print(reversed(string))

Output:

<reversed object at 0x7f61d9c81fa0>

Notice that the reversed method returns an iterable object. We can use a for loop to iterate over this object and print each character. See the example below:

# string
string = "bashir"

# for loop
for i in reversed(string):
   print(i)

Output:

r
i
h
s
a
b

Notice that the output is in reversed order, this is because the object returned by the reversed method contains the string in reversed order.

We can also join these individual characters to create a reversed string using python built-in function join(). Join method takes each of the characters and joins them together and returns as a new one string. See the example below:

# string
string = "bashir"

# printing
print("".join(reversed(string)))

Output:

rihsab

We can also create a function using the reversed and join method which takes a string and returns the reverse of it. See the following example.

# function
def reverseFunction(string):

   # return reverse
   return "".join(reversed(string))

# calling the function
print(reverseFunction("welcome to my world"))

Output:

dlrow ym ot emoclew

 

Python reverse string using for loop

The for loop in python is an iterating function. Suppose we have a sequence object like a list or string, then we can use a for loop to iterate over the items contained within that sequence. The functionality of the for loop is not very difficult, we already had used the for loop in the above program. In this section we will see how we can reverse a string using a for loop.

# string
str = "Bashir alam"

# empty string to store the reverse
reverse = ""

# for loop to iterate
for i in str:
   reverse = i+reverse
# printing
print(reverse)

Output:

mala rihsaB

In the program above, we created a string and then an empty string to store the reversed one. The for loop iterates every element of the given string, joins each character in the beginning and stores it in the reverse variable. Now let us create a function which uses a for loop to return the reverse of a given string. See the example below:

def reverseFunction(string):
   reverse = ""

   # for loop to iterate
   for i in string:
       reverse = i+reverse
   return reverse

print(reverseFunction("this is reverse function"))

Output:

noitcnuf esrever si siht

In a similar way, we can iterate over a list of strings and find the reverse. See the example below:

def reverseFunction(string):
   reverse = []

   # for loop to iterate
   for i in string:
       reverse = [i]+reverse
   return reverse

# printing
print(reverseFunction(["a", "b", "c", "d”])

Output:

['d', 'c', 'b', 'a']

 

Python reverse string using for loop

We know that the while loop takes only a single condition. When the condition evaluates to true, the while loop will continue to run and as soon as the condition is no longer true, the loop stops. In such a case, if we create a loop with the condition as True then the loop will run infinitely until a break is added. Here is a simple syntax of while loop in python

while condition :

    Statement of while loop

    . . . . . . .

    End of the Statements

Now in this section we will see how we can use a while loop to iterate over a string and find out the reverse of it.  See the example below:

# string
str1 = "Bashir"

# empty string
reverse = ''

# finding the length of string
length = len(str1) - 1
while length >= 0:

   # adding characters in reverse order
   reverse = reverse + str1[length]

   # each time subtracting 1 from length
   length = length - 1

# print
print(reverse)

Output:

rihsaB

In a similar way we can create a function which will take a string as an input and then use a while loop to iterate over it and then return the reverse of the string. See the example below:

# function
def reverseFunction(string):

   # empty string
   reverse = ''

   # finding the length of string
   length = len(string) - 1
   while length >= 0:
       # adding characters in reverse order
       reverse = reverse + string[length]

       # each time subtracting 1 from length
       length = length - 1

       # returning the reverse of string
   return reverse

# print
print(reverseFunction("this is reverse function"))

Output:

noitcnuf esrever si siht

In a similar way we can apply the same method on a list of strings to find out the reverse. See the example below which prints out the reverse of the list of strings.

# function
def reverseFunction(string):

   # empty string
   reverse = []

   # finding the length of string
   length = len(string) - 1
   while length >= 0:

       # adding characters in reverse order
       reverse = reverse + [string[length]]

       # each time subtracting 1 from length
       length = length - 1

       # returning the reverse of string
   return reverse

# print
print(reverseFunction(["a", "b", "c", "d"]))

Output:

['d', 'c', 'b', 'a']

 

Python reverse string using recursive function

Recursion is the process of defining something in terms of itself. So a recursive function in python is a function which calls itself. The following is the simple syntax of python recursive function

def function():
    Statements of function
    …
    …
    function()
function()

In this section, we will see how we can use python recursive functions to reverse python strings. See the following code which returns the reverse of the string through recursion process.

# function
def reverseFunction(string):

   # check if string has zero characters
   if len(string) == 0:

       # returns the reverse of string
       return string
   else:

       # call the function again
       return reverseFunction(string[1:]) + string[0]
# calling function
print(reverseFunction("Bashir"))

Output:

rihsaB

In a similar way we can reverse a set using the recursive function. See the example below:

# function
def reverseFunction(string):

   # check if string has zero characters
   if len(string) == 0:

       # returns the reverse of string
       return string
   else:
       # call the function again
       return reverseFunction(string[1:]) + [string[0]]

# calling function
print(reverseFunction(["b", "a", "s", "h"]))

Output:

['h', 's', 'a', 'b']

 

Python reverse string using in-place reversal algorithm

This is the classic in-place string reversal algorithm, ported to python. Because Python strings are immutable, so first we need to convert the string into a mutable list of characters so that we can perform in-place character swap:

See the following example which returns the reverse of the string using in-place reversal algorithm.

# string
string = "Bashir"

# converting into mutable object
chars = list(string)

# using for loop to iterate
for i in range(len(string) // 2):

   # swapping
   temporary = chars[i]
   chars[i] = chars[len(string) - i - 1]
   chars[len(string) - i - 1] = temporary

# printing by joining
print(''.join(chars))

Output:

rihsaB

We can create an in-place algorithm which will take a string as an argument and returns the reverse of a string.

# creating a function
def reverseFunction(string):

   # converting into mutable object
   chars = list(string)

   # using for loop to iterate
   for i in range(len(string) // 2):

       # swapping
       temporary = chars[i]
       chars[i] = chars[len(string) - i - 1]
       chars[len(string) - i - 1] = temporary

   # printing by joining
   return ''.join(chars)
# calling to function
print(reverseFunction("this is reverse function"))

Output:

noitcnuf esrever si siht

 

Summary

In Python, strings are arrays of bytes representing Unicode characters. Everything that we write inside single, double, or triple quotation marks is considered as a string. Python has many built-in functions, however, it does not have any built-in function to find the reverse of a string. That does not mean we cannot find the reverse of a python string. There are many other ways to find the reverse and in this tutorial, we cover most of them. We learned various methods of finding the reverse of a python string using different examples.

 

Further Reading Section

Python reverse string
Reverse string in Python
Python strings

 

Views: 0

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment