In this tutorial, you’ll learn how to reverse a string in Python. In fact, you’ll learn six different ways to accomplish this. Don’t worry though, you won’t be left guessing which way is the best. You’ll learn what the best method is for usability, readability, and speed.
It might seem like Python should have a
string.reverse() method. However, because Python strings are immutable, this isn’t the case.
By the end of this tutorial, you’ll have learned the following:
- Six different ways to reverse a string in Python
- When to use which approach
The Quick Answer: Use String Indexing to Reverse a String in Python
Table of Contents
Python String Slicing: The Best Way to Reverse a String
The best way to reverse a string in Python is to use string indexing, with a step of -1. For example, using a string such as
text='datagy', we can reverse it using
backward = text[::-1].
Notice here that we had to assign the string to a variable (even if it we had reassigned it to itself). Because Python strings are immutable, not re-assigning the string would simply iterate over this.
# Reverse a Python String: String Indexingtext = 'datagy'backward = text[::-1]print(backward)# Returns: ygatad
How does this method work? By using string slicing, we iterate over each element of the string in reverse order. By default, slicing works in the format of
stop are omitted, the entire string is indexed.
Custom Function for Readability When Reversing a Python String
A custom function can allow your code to be more readable. If you want to make it clear that your intention is to reverse a string, creating a custom function can make that intention clear.
Let’s see how we can create a custom Python function to reverse a string:
# Create a Custom Function to Reverse a Stringdef reverse_string(text): if type(text) == str: return text[::-1] else: raise TypeError('Please pass in a string') text = 'datagy'backward = reverse_string(text)print(backward)# Returns: ygatad
Let’s break down what we’re doing with the function above:
- We define a function
reverse_string(text), which takes a single argument. We have defined the argument to be named
text, to make it clear that it should take a string.
- Within the function, we first check the type of the argument. If it’s a string, we use string indexing to return the reversed text.
- If the argument is a string, we raised a
TypeErrorand return a custom message indicating that you need to pass in a string.
Why is this method good? This method makes it incredibly clear that we want to reverse a string. This is especially helpful for beginners who may need a bit of help following the code.
What Is the Fastest Way to Reverse a String in Python?
In the following sections, we’ll explore different ways in which you can reverse a string in Python. These methods are included primarily for completeness. Before diving into these methods, let’s explore which method is the fastest.
|Method||Time for 1,000 Character String (µs)|
We can see that string slicing is by far the fastest way of reversing a string. In fact, it’s significantly faster than other options (over 700 times faster than the slowest method, recursion). Because of this, string slicing is the method I’d recommend the most.
Other Ways of Reversing a String in Python
In the following sections, you’ll learn how to reverse a string using other methods. I am including these methods here only for the purpose of completeness. I wouldn’t recommend the methods covered below in practice. However, they are helpful to know and can be useful in coding interviews.
Reversing a Python String with a For Loop
Because Python strings are iterable (as is made clear by our example of using string indexing), we can loop over them using a Python for loop.
By using a for loop, we can iterate over each character in the string and create a reversed string. Let’s see what this process looks like:
# Reversing a String with a Python for looptext = 'datagy'reversed_string = ''for character in text: reversed_string = character + reversed_stringprint(reversed_string)# Returns: ygatad
Let’s break down how we’re using a for loop to reverse a Python string:
- We initialize both a string (
text) and an empty string (
- We then loop over each character in the string
- We add the current reversed string to the character of the loop
- Finally, we print the reversed string
If you’re having a hard time visualizing what this looks like, let’s see what each of the printed statements looks like:
# Visualizing what this looks liketext = 'datagy'reversed_string = ''for character in text: reversed_string = character + reversed_string print(reversed_string)# Returns:# d# ad# tad# atad# gatad# ygatad
We can see that each character is accessed and the currently reversed parts are added to the end of that string.
Reversing a Python String with a While Loop
Python while loops are methods of indefinite iteration, meaning that they will continue to iterate until a condition is met. Let’s see how we can use a while loop to reverse a string in Python:
# Reversing a String with a Python while looptext = 'datagy'reversed_string = ''i = len(text)while i > 0: reversed_string += text[i] i -= 1print(reversed_string)# Returns: ygatad
This example looks a little more complicated than our for loop (and it is!). Let’s see what’s going on under the hood to see how this approach works:
- We instantiate three variables:
textwhich contains our string,
reversed_string, which is an empty string, and
i, which is the length of the string
- We then create a while loop that continues iterating while the value of
iis greater than 0 (meaning there are still characters left)
- We use the augmented assignment operator += to add characters one by one from the end of the string
- Finally, we subtract 1 from the value of
ito move from right to left by one character.
Reverse a String Using the Python reversed Function
Python has a built-in function,
reversed(), which reverses an iterable item (such as a list or a string) and returns a reversed object.
We can use this function together with the string
.join() method to return a string in backward order. Let’s see how we can reverse a string using the
# Reversing a String with Python reversed()text = 'datagy'reversed_string = ''.join(reversed(text))print(reversed_string)# Returns: ygatad
There’s quite a bit going on in this code so let’s break it down a little bite:
- We create our string in the variable
- We then pass the string into the
- Finally, we re-join the object into a string by using the
This is a very clean method that works well. It’s especially nice because it has error handling built right in. This means that it will raise a
TypeError if the object passed in isn’t iterable.
Reverse a Python String Using Recursion
Python recursion can be an intimidating concept, but it’s a great one to have at the back of your mind for coding interviews. I’ll admit, I’m including this example mostly for fun. I can’t really see myself ever using this method outside of an interview.
Let’s take a look at what our recursive method looks like and then dive into how it works. Recursion works by creating a function that calls itself until it hits a base case.
# Reverse a String in Python with Recursiona_string = 'datagy'def reverse_a_string(a_string): if len(a_string) == 1: return a_string return reverse_a_string(a_string[1:]) + a_string[:1]reversed_string = reverse_a_string(a_string)print(reversed_string)# Returns: ygatad
In the example above, the
reverse_a_string() function calls itself continuously until the base case is reached (where the length of the string is equal to 1).
This method is by far the least readable and also the longest. Because of this, I don’t recommend using this approach, unless you absolutely need to.
In this tutorial, you learned how to use Python to reverse a string. This is an important skill to know, especially in beginner programming interviews. You learned the best method to accomplish this, string indexing, and how to convert this to a very readable function to help guide readers of your code. You learned some alternative methods, including using for loops and while loops, as well as list methods and recursion.
To learn more about string indexing in Python, check out the official documentation here.
To learn more about related topics, check out the resources below:
- How to Reverse a Python List (6 Ways)
- Python: Reverse a Number (3 Easy Ways)
- Python List sort(): An In-Depth Guide to Sorting Lists