How to Reverse a String in Python

How to Reverse a String in Python

7 mins read3.4K Views Comment
Updated on Mar 3, 2023 17:37 IST

In Python programming, strings are a sequence of characters or symbols. As a beginner practicing Python string operations, you will often come across problems that need you to work with strings in reverse order. This article will focus on the different methods supported in Python to help you learn how to reverse a string in Python quickly and efficiently.

2022_06_python-reverse-a-string.jpg

We will be covering the following sections today in How to Reverse a String in Python:

What is a Python String?

A Python string is simply an array of items. These items are nothing but bytes representing Unicode characters or symbols. In Python, there is no character data type, and so a character is simply represented as a string of one item (length = 1). Square brackets can be used to access elements of the string.

Python does not provide any built-in function to reverse a string. But there are multiple ways in which we can manually do that.

2022_06_python-reversing-a-string.jpg

Also, Read: Introduction to Python – Features, Use Cases, Resources, and Applications

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
3 months
– / –
2 weeks
– / –
16 weeks
β‚Ή1.7 K
3 months
– / –
– / –
β‚Ή4.24 K
2 weeks
β‚Ή3 K
3 weeks
– / –
4 months

Methods to Reverse a String in Python

Let’s understand how to reverse a string in Python using various methods:

1. Using For Loop

#Define a function
def rev_func(string):
    # Declare a string variable 
    revstr = ''
 
    #Iterate string with for loop
    for x in string:
        # Appending chars in reverse order
        revstr = x + revstr
    return revstr
 
string = str(input())
 
#Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', rev_func(string))

For example, say we enter the string β€˜PYTHON’:

output1

What have we done here? 

  • In the above code, we start by declaring the rev_func() function and passing the string argument. 
  • Then, in the function body, we declare an empty string variable revstr that will store the reversed string.
  • Next, we use the for loop to iterate all characters of the input string to concatenate each element stored in the revstr variable.
  • Once, the for loop has completed execution, it returns the reversed string to the caller function, as shown in the output.  

2. Using While Loop

#Define a function
def rev_func(string):
    #Declare an empty string variable 
    revstr = ''
 
    #Find length of a string and save in count variable  
    count = len(string) - 1
    #Run the loop with last string index 
    while count >= 0:
        print('String Index: ',string[count],' - ', count)
 
        #Appending chars in reverse order
        revstr = revstr + string[count]
 
        #Decrement string index by 1
        count = count - 1
    return revstr
 
string = str(input())
 
#Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', rev_func(string))
output2

What have we done here? 

  • In the above code again, we start by declaring the rev_func() function and passing the string argument. 
  • Then, in the function body, we declare an empty string variable revstr that will store the reversed string.
  • Next, we subtract the length of the string by one, using the len() method, because the string index starts from zero. We store the string index in the count variable.  
  • Then, we run the while loop which checks if the count is greater than 0. While this condition is True, the characters of the string along with their index values are displayed. 
  • The next line in the while loop appends all elements in reverse order into the revstr variable. 
  • Next, the string index is decremented by 1 before returning the final reversed string to the caller function, as shown in the output.

3. A Slice Operator

A slice operator accepts three arguments – start, stop, and step. In this case, we will not provide a start and stop index. So, the default values will be considered which are start = 0 and stop = n-1. 

The step value will be specified as -1, which means that the string will traverse from the end to the index position 1. 

#Define a function
def rev_func(string):
    return string[::-1]
 
string = str(input())
 
#Print Original and Reverse strings
print('Original String: ', string)
print('Reverse String: ', rev_func(string))
output3

What have we done here? 

  • In the above code, we are slicing the input string by moving in a backward step from the end to the beginning of the string. 
  • We declare the rev_func() function and pass the string argument to it.
  • Inside the function body, we use a slice operator to print the reverse of a string –

string[::-1] means that the slicing will start from the end of the string with one step back each time.

  • Once the string is fully traversed, its reverse is returned. The print statement then calls this function to display the reversed string. 

4. Using Reverse and Join Method

In this method, we will use the built-in reversed() method to cycle through the characters of the string in reverse order.

Then, we will use the join() method to join all the characters from the reversed iteration into a new string variable.

#Define a function
def rev_func(string):
    #Join reverse object of original string
    revstr = ''.join(reversed(string))
    return revstr
 
string = str(input())
 
#Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', rev_func(string))
output4

What have we done here? 

  • In the above code again, we start by declaring the rev_func() function and passing the string argument. 
  • Then, in the function body, we pass the input string using the reversed() method to iterate the characters of the string in reverse. 
  • The reversed characters are then merged by applying the join() method and stored in the revstr variable. The function rev_func() returns this revstr variable.
  • The print statement then calls this function to display the reversed string. 

5. List Comprehension

In Python, there is a reverse() function to reverse the items of a list. 

In this example, we are going to make use of this method to get the reverse of a string by converting the string to a Python list. Then, we will reverse the list before converting it back to a string using the join() method. 

#Define a function
def rev_func(string):
    #Convert string to list
    revstr  = list(string)
 
    #Print List
    print(revstr)
 
    #Reverse List with reverse() function
    revstr.reverse()
 
    #Print reverse list
    print(revstr)
 
    #Convert list to string with join() function 
    return ''.join(revstr)
 
string = str(input())
 
# Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', rev_func(string))
 
output5

What have we done here? 

  • In the above code, we start by declaring the rev_func() function and passing the string argument. 
  • Then, we convert the string parameter to a list using the list() method and store it in the revstr variable. The value of this variable is printed on the screen.
  • Next, the characters of the list are reversed using the in-built reverse() method and stored in the revstr variable again. The value of this variable is printed again on the screen.
  • Now that the list is reversed, it is merged using the join() method and converted back into the reversed string.
  • The reversed string is returned to the caller function, as shown in the output.

6. Using Recursion Method

In this method, we reverse a string using recursion which is a process where the function calls itself. Let’s see how this is done:

#Define a function
def rev_func(string):
    #Check the length of the string   
    if len(string) == 0:
        return string   
    else:   
        return reverse(string[1:]) + string[0]   
 
string = "company"
 
#Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', reverse(string))
output6

What have we done here? 

  • In the above code, we declare the rev_func() function that accepts a string argument. 
  • Then, in the function body, we define the base condition of recursion –
    • If the length of a string is 0, then the string is returned as-is. 
    • If not equal to 0, then we call the function recursively to slice the part of the string except the first character and then concatenate the first character to the end of the sliced string.

Also Read: Reverse a String in Java

Endnotes

Hope this article will be helpful for you to understand how to reverse a Python string. An important point to be noted is that slicing is considered the most efficient way to reverse a string as it is simpler and quicker than other methods. If you wish to learn more about Python and practice Python programming, you can explore related articles here.

Top Trending Tech Articles:
Career Opportunities after BTech | Online Python Compiler | What is Coding | Queue Data Structure | Top Programming Language | Trending DevOps Tools | Highest Paid IT Jobs | Most In Demand IT Skills | Networking Interview Questions | Features of Java | Basic Linux Commands | Amazon Interview Questions

______________

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio