In this tutorial, you’ll learn how to use Python to reverse a string. Knowing how to work with strings is an incredibly useful skill. In particular, reversing a string is a problem that will often come up in programming interviews.
You’ll learn why reversing a string doesn’t work as you’d expect, and different ways you can use to reverse a string in Python. You’ll learn how to use string indexing, list reversing, a Python for loop, a while loop, recursion, and a custom function to make your code more readable.
The Quick Answer: Use String Indexing to Reverse a String in Python
Why Strings are Tricky to Reverse in Python
Strings in Python are
immutable, meaning that they cannot be changed. This is different than other objects, such as lists, which allow for us to easily reverse them, using built-in methods.
In order to reverse a string, we need create a new string, rather than modify its original.
This is an important concept to understand, since its a question that frequently occurs in programming interviews. While you may not often encounter this in your day-to-day programming adventures, it’s important to keep in the back of your mind.
Now, let’s dive into learning how to reverse a string with Python.
Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!
Reverse a Python String with String Indexing
Python strings are
indexed objects, meaning that we can access their items using their index.
Python indices begin at
0 on increase by
1. Similarly, we can access an object’s last item by accessing its negative index, which begins by
-1, and decreases by
One great advantage of Python indexing is that we can use a
step variable to iterate over an object that is indexed. The
step variable is the third item in an index, which allows us to set how we move over an item.
Now that you have a strong understanding of how string indexing works in Python, let’s see how we can use it to accomplish our goal:
# Reverse a String in Python with String Indexing a_string = 'datagy' reversed_string = a_string[::-1] print(reversed_string) # Returns: ygatad
We can see here that we were able to reverse our string. This worked because we set the optional third parameter, the
step parameter, to
-1. This allows us to traverse the string in a negative order.
In the next section, you’ll learn how to create a custom function that makes this approach easier to read.
Create a Custom Function to Reverse Python Strings
Because Python doesn’t have a clear, understandable method to reverse strings, it may be helpful to you and your code’s readers to create one. While it may seem trivial to do this, as the code will only be a single line, it makes it immediately clear what your code is doing.
Let’s see how we can use the string indexing method and create a custom function:
# Reverse a String in Python with String Indexing with a Custom Function def reverse_string(a_string): return a_string[::-1] a_string = 'datagy' reversed_string = reverse_string(a_string) print(reversed_string) # Returns: ygatad
Using this method increases readability of your code. In the next section, you’ll learn how to use Python lists to accomplish this goal!
Want to learn how to use the Python
zip() function to iterate over two lists? This tutorial teaches you exactly what the
zip() function does and shows you some creative ways to use the function.
Use Python Lists to Reverse a String
Because Python strings are iterable objects, we can easily turn them into lists. Lists in Python come with built-in tools to allow us to reverse them. You can learn all about these methods in my in-depth tutorial, which guides you through six different ways to reverse a list in Python.
Let’s see how we can do this in Python:
# Reverse a String in Python with lists a_string = 'datagy' a_list = list(a_string).reverse() a_list.reverse() reversed_string = ''.join(a_list) print(reversed_string) # Returns: ygatad
Let’s break down what we’ve done here:
- We converted out string to a list,
- We then used the
.reverse()method to reverse out list,
- Finally, we converted our list back to a string
In the next section, you’ll learn how to use a Python for loop for this purpose.
Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.
Use a Python For Loop to Reverse a String
We can also use a Python for loop to return a string in its backwards order.
In order to do this, we can loop over each item in its reverse order and append it to a new string.
# Reverse a String in Python with a for loop a_string = 'datagy' reversed_string = '' for item in a_string: reversed_string = item + reversed_string print(reversed_string) # Returns: ygatad
In the next section, you’ll learn how to use a while loop to reverse a string in Python.
Use a Python While Loop to Reverse a String
A Python while loop can also be used to return a string in its backwards order.
Let’s take a look at how we can do this and then explore why it works:
# Reverse a String in Python with a while loop a_string = 'datagy' reversed_string = '' i = len(a_string) - 1 while i >= 0: reversed_string += a_string[i] i -= 1 print(reversed_string) # Returns: ygatad
Let’s take a look at why this works:
- We run our loop while our index is greater or equal to 0
- We start at the last index and move towards the lowest index, 0
- For each string we encounter, we append it to a new list
- We then decrease our counter,
i, by 1
In the next section, you’ll learn how to use recursion to reverse a string.
Want to learn more about calculating the square root in Python? Check out my tutorial here, which will teach you different ways of calculating the square root, both without Python functions and with the help of functions.
Reverse a String with Python Recursion
Recursion can be a difficult concept to wrap your mind around, but also a helpful tool once you understand it.
To use a recursive method, we need to create a function that will call itself until a certain condition is met.
Let’s see how we can use recursion to reverse our string:
# Reverse a String in Python with Recursion a_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
Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.
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.