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.

Download  Run Code

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.

Download  Run Code

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:

Download  Run Code

4. Using reduce() function

Another option is to perform a reduction operation using the functools.reduce function.

Download  Run Code

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.

Download  Run Code

6. Using reversed range

Finally, you can iterate over the string in reverse order using reversed range and yield the results:

Download  Run Code

That’s all about reversing a string in Python.