To reverse a string in Python, you can use negative slicing as follows:
For example, let’s reverse a string “Testing”:
s = "Testing" # Use negative slicing to reverse a string rev = s[::-1] print(rev)
To learn more approaches to reverse a string in Python, feel free to read along. You’ll also better understand how the above example really works. If you want to have a quick look, please check this gist to see the codes.
Keep in mind the above example shows the best way to reverse a string. The rest of the methods are useful for educational purposes and to sharpen your Python skills. But if you’re looking for the easiest solution, you’re good with the above example already.
Let’s jump into it!
5 Ways to Reverse a String in Python
Here are 5 different ways for reversing a string in Python.
Remember, the slicing approach is the shortest and most Pythonic way to reverse a string. Use it unless you’re forced to do it in another way. At the end of this guide, you will see how the different string-reversing approaches perform against one another
1. Slicing with Negative Index
The fastest and easiest way to reverse a string in Python is by using the slicing notation with a negative index [::-1].
Here’s a function that reverses a string with the reverse slicing syntax:
def reverse_slicing(s): return s[::-1]
Let’s take a closer look at how this function works.
How Does It Work?
In Python, you can access parts of iterables using the slicing notation:
- start is the starting value of the slice. The default start index is at the first element. This value can be negative.
- end is the exclusive end value of the slice. The default end index is at the last element. This value can be negative.
- step is the step size of the slice. The default value is 1. To invert the direction, you can specify a negative step.
Slicing allows you to access for example the first 5 values of a list.
One handy feature of the slicing is you can omit start/end/step values altogether. If you don’t specify start/stop, the slicing will start from the first value and end at the last value.
So the string reversal notation string[::-1] means start from the first character and end to the last one but in a reversed order.
I recommend checking What Does [::-1] Mean in Python to find a more detailed explanation with examples.
Another option to reverse a string in Python is by using loops. More specifically, you can use a for or a while loop. With both approaches, the idea is the same:
- Initialize an empty result string.
- Loop through each character of the original string.
- Add each character to the front of the result string.
2.1. For Loop Example
Here’s a function that reverses a string using a for loop:
def reverse_for_loop(s): s1 = "" for c in s: s1 = c + s1 return s1
2.2. While Loop Example
Here’s a function that uses while loop to reverse a string:
def reverse_while_loop(s): s1 = "" l = len(s) - 1 while l >= 0: s1 += s[l] l -= 1 return s1
3. Join with str.join() Method
In Python, there’s a built-in reversed() function you can call on iterables, such as strings or lists. To reverse a string, you need to combine this method with the str.join() method.
Here’s a function that calls the reversed() function in conjunction with the .join() method:
def reverse_with_join(s): return "".join(reversed(s))
How Does It Work?
The reversed() takes a string and returns a special reversed object that stores the characters in a reversed order.
Notice that the result is thus not a string but an iterator object.
To convert the reversed characters into a string, you can call the str.join() method by using an empty string as a separator. The join() method takes the characters from the reversed object and merges them into a string which is the reversed version of the original string.
Feel free to read more about iterators and iterables.
4. The list.reverse() Approach
Another way to reverse a string is by converting it to a list of characters, reversing the list, and converting it back to a string.
Here’s a function that uses the list.reverse() method to reverse a string:
def reverse_with_list(s): s_as_list = list(s) s_as_list.reverse() return "".join(s_as_list)
Let’s break down the code so you can better understand what’s going on:
- First you convert a string to a list of characters.
- Then you call the list.reverse() method on the characters. This flips the order of the characters.
- Finally, you convert the reversed character list back to a string.
Last but not least, you can practice your recursion skills by reversing a string using a recursive function (a function that calls itself).
Here’s an example implementation of a function that recursively reverses a string:
def reverse_recursively(s): if len(s) == 0: return s else: return reverse_recursively(s[1:]) + s
The idea of this function is very similar to the while loop approach you saw earlier. Besides, it uses the slicing notation to access all but the first letter of the string.
If you’re not familiar with recursion, I recommend reading a separate guide about the topic. To keep it in scope, you won’t learn how the callstack works in the above function.
Here are the performance comparisons between the above methods for reversing strings in Python.
To repeat the performance tests on your system:
- Create a Python file called reverse_strings.py.
- Copy-paste all the string reversal methods to the file.
- Open up the command line window or terminal.
- Run the terminal commands below to see the execution times.
$ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_slicing("This is just a tests")' 100000 loops, best of 5: 0.377 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_for_loop("This is just a tests")' 100000 loops, best of 5: 1.84 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_while_loop("This is just a tests")' 100000 loops, best of 5: 2.94 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_with_join("This is just a tests")' 100000 loops, best of 5: 1.01 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_with_list("This is just a tests")' 100000 loops, best of 5: 0.87 usec per loop $ python3 -m timeit --number 100000 --unit usec 'import reverse_strings' 'reverse_strings.reverse_recursively("This is just a tests")' 100000 loops, best of 5: 6.29 usec per loop
As you can see, the slicing approach (str[::-1]) is the fastest one by a mile. Also, because it’s the easiest one to use, it really makes sense to stick with that unless you’re forced to do it differently.
Today you learned how to reverse a string in Python.
To recap, you can use slicing with a negative index to easily reverse a string in Python. Besides, there are lots of other approaches, but each of them requires you to write more code. Moreover, the alternative approaches are slower than the slicing approach.
Thanks for reading. Happy coding!
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
- Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)