Reverse a Python string
This post will discuss how to reverse a string in Python.
Reversing a string cannot be done in-place since strings are immutable in Python. However, you can create a reversed copy of a string. This post provides an overview of several functions to accomplish this.
1. Using Extended Slices
The Pythonic solution to reverse a string uses the extended slice syntax [start:stop:step], which supports an optional third step argument. The idea is to specify a step of -1 and substitute None for start and stop.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': input = "Reverse me" rev = input[::-1] print(rev) # em esreveR |
2. Using reversed() function
Another option is to use the built-in function reversed(), which can take a string and returns a reverse iterator. To get a reversed copy of a string, call the str.join() function.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': input = "Reverse me" rev = ''.join(reversed(input)) print(rev) # em esreveR |
3. Using Recursion
You can also reverse a string with recursion. The idea is to extract the first character from the string and recur for the remaining characters. Then append the first character at the end of the string. This is demonstrated below using slicing:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def reverse(input): if len(input) <= 1: return input return reverse(input[1:]) + input[0] if __name__ == '__main__': input = "Reverse me" rev = reverse(input) print(rev) # em esreveR |
4. Using reduce() function
Another option is to perform a reduction operation using the functools.reduce function.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
from functools import reduce def reverse(input): return reduce(lambda x, y: y + x, input) if __name__ == '__main__': input = "Reverse me" rev = reverse(input) print(rev) # em esreveR |
5. Using deque
Another plausible way of reversing a string involves deque. The idea is to create an empty deque and then extend the left side of the deque by appending characters from the string. You can easily do this with the extendleft() function. Finally, join characters in the deque to get a new string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from collections import deque def reverse(input): d = deque() d.extendleft(input) return ''.join(d) if __name__ == '__main__': input = "Reverse me" rev = reverse(input) print(rev) # em esreveR |
6. Using reversed range
Finally, you can iterate over the string in reverse order using reversed range and yield the results:
|
1 2 3 4 5 6 7 8 9 10 11 |
def reverse(input): for i in reversed(range(len(input))): yield input[i] if __name__ == '__main__': input = "Reverse me" rev = "".join(reverse(input)) print(rev) # em esreveR |
That’s all about reversing a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)