Reverse Strings in Python: reversed(), Slicing, and More

Reverse Strings in Python: reversed(), Slicing, and More

by Leodanis Pozo Ramos basics best-practices python

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Reversing Strings in Python

When you’re using Python strings often in your code, you may face the need to work with them in reverse order. Python includes a few handy tools and techniques that can help you out in these situations. With them, you’ll be able to build reversed copies of existing strings quickly and efficiently.

Knowing about these tools and techniques for reversing strings in Python will help you improve your proficiency as a Python developer.

In this tutorial, you’ll learn how to:

  • Quickly build reversed strings through slicing
  • Create reversed copies of existing strings using reversed() and .join()
  • Use iteration and recursion to reverse existing strings manually
  • Perform reverse iteration over your strings
  • Sort your strings in reverse order using sorted()

To make the most out of this tutorial, you should know the basics of strings, for and while loops, and recursion.

Reversing Strings With Core Python Tools

Working with Python strings in reverse order can be a requirement in some particular situations. For example, say you have a string "ABCDEF" and you want a fast way to reverse it to get "FEDCBA". What Python tools can you use to help?

Strings are immutable in Python, so reversing a given string in place isn’t possible. You’ll need to create reversed copies of your target strings to meet the requirement.

Python provides two straightforward ways to reverse strings. Since strings are sequences, they’re indexable, sliceable, and iterable. These features allow you to use slicing to directly generate a copy of a given string in reverse order. The second option is to use the built-in function reversed() to create an iterator that yields the characters of an input string in reverse order.

Reversing Strings Through Slicing

Slicing is a useful technique that allows you to extract items from a given sequence using different combinations of integer indices known as offsets. When it comes to slicing strings, these offsets define the index of the first character in the slicing, the index of the character that stops the slicing, and a value that defines how many characters you want to jump through in each iteration.

To slice a string, you can use the following syntax:

Python
a_string[start:stop:step]

Your offsets are start, stop, and step. This expression extracts all the characters from start to stop − 1 by step. You’re going to look more deeply at what all this means in just a moment.

All the offsets are optional, and they have the following default values:

Offset Default Value
start 0
stop len(a_string)
step 1

Here, start represents the index of the first character in the slice, while stop holds the index that stops the slicing operation. The third offset, step, allows you to decide how many characters the slicing will jump through on each iteration.

The step offset allows you to fine-tune how you extract desired characters from a string while skipping others:

Python
>>> letters = "AaBbCcDd"

>>> # Get all characters relying on default offsets
>>> letters[::]
'AaBbCcDd'
>>> letters[:]
'AaBbCcDd'

>>> # Get every other character from 0 to the end
>>> letters[::2]
'ABCD'

>>> # Get every other character from 1 to the end
>>> letters[1::2]
'abcd'

Here, you first slice letters without providing explicit offset values to get a full copy of the original string. To this end, you can also use a slicing that omits the second colon (:). With step equal to 2, the slicing gets every other character from the target string. You can play around with different offsets to get a better sense of how slicing works.

Why are slicing and this third offset relevant to reversing strings in Python? The answer lies in how step works with negative values. If you provide a negative value to step, then the slicing runs backward, meaning from right to left.

For example, if you set step equal to -1, then you can build a slice that retrieves all the characters in reverse order:

Python
>>> letters = "ABCDEF"

>>> letters[::-1]
'FEDCBA'

>>> letters
'ABCDEF'

This slicing returns all the characters from the right end of the string, where the index is equal to len(letters) - 1, back to the left end of the string, where the index is 0. When you use this trick, you get a copy of the original string in reverse order without affecting the original content of letters.

Another technique to create a reversed copy of an existing string is to use slice(). The signature of this built-in function is the following:

Python
slice(start, stop, step)

This function takes three arguments, with the same meaning of the offsets in the slicing operator, and returns a slice object representing the set of indices that result from calling range(start, stop, step).

You can use slice() to emulate the slicing [::-1] and reverse your strings quickly. Go ahead and run the following call to slice() inside square brackets:

Python
>>> letters = "ABCDEF"

>>> letters[slice(None, None, -1)]
'FEDCBA'

Passing None to the first two arguments of slice() tells the function that you want to rely on its internal default behavior, which is the same as a standard slicing with no values for start and stop. In other words, passing None to start and stop means that you want a slice from the left end to the right end of the underlying sequence.

Reversing Strings With .join() and reversed()

The second and arguably the most Pythonic approach to reversing strings is to use reversed() along with str.join(). If you pass a string to reversed(), you get an iterator that yields characters in reverse order:

Python
>>> greeting = reversed("Hello, World!")

>>> next(greeting)
'!'
>>> next(greeting)
'd'
>>> next(greeting)
'l'

When you call next() with greeting as an argument, you get each character from the right end of the original string.

An important point to note about reversed() is that the resulting iterator yields characters directly from the original string. In other words, it doesn’t create a new reversed string but reads characters backward from the existing one. This behavior is fairly efficient in terms of memory consumption and can be a fundamental win in some contexts and situations, such as iteration.

You can use the iterator that you get from calling reversed() directly as an argument to .join():

Python
>>> "".join(reversed("Hello, World!"))
'!dlroW ,olleH'

In this single-line expression, you pass the result of calling reversed() directly as an argument to .join(). As a result, you get a reversed copy of the original input string. This combination of reversed() and .join() is an excellent option for reversing strings.

Generating Reversed Strings by Hand

So far, you’ve learned about core Python tools and techniques to reverse strings quickly. Most of the time, they’ll be your way to go. However, you might need to reverse a string by hand at some point in your coding adventure.

In this section, you’ll learn how to reverse strings using explicit loops and recursion. The final technique uses a functional programming approach with the help of Python’s reduce() function.

Reversing Strings in a Loop

The first technique you’ll use to reverse a string involves a for loop and the concatenation operator (+). With two strings as operands, this operator returns a new string that results from joining the original ones. The whole operation is known as concatenation.

Here’s a function that takes a string and reverses it in a loop using concatenation:

Python
>>> def reversed_string(text):
...     result = ""
...     for char in text:
...         result = char + result
...     return result
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

In every iteration, the loop takes a subsequent character, char, from text and concatenates it with the current content of result. Note that result initially holds an empty string (""). The new intermediate string is then reassigned to result. At the end of the loop, result holds a new string as a reversed copy of the original one.

If you prefer using a while loop, then here’s what you can do to build a reversed copy of a given string:

Python
>>> def reversed_string(text):
...     result = ""
...     index = len(text) - 1
...     while index >= 0:
...         result += text[index]
...         index -= 1
...     return result
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

Here, you first compute the index of the last character in the input string by using len(). The loop iterates from index down to and including 0. In every iteration, you use the augmented assignment operator (+=) to create an intermediate string that concatenates the content of result with the corresponding character from text. Again, the final result is a new string that results from reversing the input string.

Reversing Strings With Recursion

You can also use recursion to reverse strings. Recursion is when a function calls itself in its own body. To prevent infinite recursion, you should provide a base case that produces a result without calling the function again. The second component is the recursive case, which starts the recursive loop and performs most of the computation.

Here’s how you can define a recursive function that returns a reversed copy of a given string:

Python
>>> def reversed_string(text):
...     if len(text) == 1:
...         return text
...     return reversed_string(text[1:]) + text[:1]
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

In this example, you first check for the base case. If the input string has exactly one character, you return the string back to the caller.

The last statement, which is the recursive case, calls reversed_string() itself. The call uses the slice text[1:] of the input string as an argument. This slice contains all the characters in text, except for the first one. The next step is to add the result of the recursive call together with the single-character string text[:1], which contains the first character of text.

A significant issue to note in the example above is that if you pass in a long string as an argument to reversed_string(), then you’ll get a RecursionError:

Python
>>> very_long_greeting = "Hello, World!" * 1_000

>>> reversed_string(very_long_greeting)
Traceback (most recent call last):
    ...
RecursionError: maximum recursion depth exceeded while calling a Python object

Hitting Python’s default recursion limit is an important issue that you should consider in your code. However, if you really need to use recursion, then you still have the option to set the recursion limit manually.

You can check the recursion limit of your current Python interpreter by calling getrecursionlimit() from sys. By default, this value is usually 1000. You can tweak this limit using setrecursionlimit() from the same module, sys. With these functions, you can configure the Python environment so that your recursive solution can work. Go ahead and give it a try!

Using reduce() to Reverse Strings

If you prefer using a functional programming approach, you can use reduce() from functools to reverse strings. Python’s reduce() takes a folding or reduction function and an iterable as arguments. Then it applies the provided function to the items in the input iterable and returns a single cumulative value.

Here’s how you can take advantage of reduce() to reverse strings:

Python
>>> from functools import reduce

>>> def reversed_string(text):
...     return reduce(lambda a, b: b + a, text)
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

In this example, the lambda function takes two strings and concatenates them in reverse order. The call to reduce() applies the lambda to text in a loop and builds a reversed copy of the original string.

Iterating Through Strings in Reverse

Sometimes you might want to iterate through existing strings in reverse order, a technique typically known as reverse iteration. Depending on your specific needs, you can do reverse iteration on strings by using one of the following options:

  • The reversed() built-in function
  • The slicing operator, [::-1]

Reverse iteration is arguably the most common use case of these tools, so in the following few sections, you’ll learn about how to use them in an iteration context.

The reversed() Built-in Function

The most readable and Pythonic approach to iterate over a string in reverse order is to use reversed(). You already learned about this function a few moments ago when you used it along with .join() to create reversed strings.

However, the main intent and use case of reversed() is to support reverse iteration on Python iterables. With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.

Here’s how you can iterate over a string in reverse order with reversed():

Python
>>> greeting = "Hello, World!"

>>> for char in reversed(greeting):
...     print(char)
...
!
d
l
r
o
W

,
o
l
l
e
H

>>> reversed(greeting)
<reversed object at 0x7f17aa89e070>

The for loop in this example is very readable. The name of reversed() clearly expresses its intent and communicates that the function doesn’t produce any side effects on the input data. Since reversed() returns an iterator, the loop is also efficient regarding memory usage.

The Slicing Operator, [::-1]

The second approach to perform reverse iteration over strings is to use the extended slicing syntax you saw before in the a_string[::-1] example. Even though this approach won’t favor memory efficiency and readability, it still provides a quick way to iterate over a reversed copy of an existing string:

Python
>>> greeting = "Hello, World!"

>>> for char in greeting[::-1]:
...     print(char)
...
!
d
l
r
o
W

,
o
l
l
e
H

>>> greeting[::-1]
'!dlroW ,olleH'

In this example, you apply the slicing operator on greeting to create a reversed copy of it. Then you use that new reversed string to feed the loop. In this case, you’re iterating over a new reversed string, so this solution is less memory-efficient than using reversed().

Creating a Custom Reversible String

If you’ve ever tried to reverse a Python list, then you know that lists have a handy method called .reverse() that reverses the underlying list in place. Since strings are immutable in Python, they don’t provide a similar method.

However, you can still create a custom string subclass with a .reverse() method that mimics list.reverse(). Here’s how you can do that:

Python
>>> from collections import UserString

>>> class ReversibleString(UserString):
...     def reverse(self):
...         self.data = self.data[::-1]
...

ReversibleString inherits from UserString, which is a class from the collections module. UserString is a wrapper around the str built-in data type. It was specially designed for creating subclasses of str. UserString is handy when you need to create custom string-like classes with additional functionalities.

UserString provides the same functionality as a regular string. It also adds a public attribute called .data that holds and gives you access to the wrapped string object.

Inside ReversibleString, you create .reverse(). This method reverses the wrapped string in .data and reassigns the result back to .data. From the outside, calling .reverse() works like reversing the string in place. However, what it actually does is create a new string containing the original data in reverse order.

Here’s how ReversibleString works in practice:

Python
>>> text = ReversibleString("Hello, World!")
>>> text
'Hello, World!'

>>> # Reverse the string in place
>>> text.reverse()
>>> text
'!dlroW ,olleH'

When you call .reverse() on text, the method acts as if you’re doing an in-place mutation of the underlying string. However, you’re actually creating a new string and assigning it back to the wrapped string. Note that text now holds the original string in reverse order.

Since UserString provides the same functionality as its superclass str, you can use reversed() out of the box to perform reverse iteration:

Python
>>> text = ReversibleString("Hello, World!")

>>> # Support reverse iteration out of the box
>>> for char in reversed(text):
...     print(char)
...
!
d
l
r
o
W

,
o
l
l
e
H

>>> text
"Hello, World!"

Here, you call reversed() with text as an argument to feed a for loop. This call works as expected and returns the corresponding iterator because UserString inherits the required behavior from str. Note that calling reversed() doesn’t affect the original string.

Sorting Python Strings in Reverse Order

The last topic you’ll learn about is how to sort the characters of a string in reverse order. This can be handy when you’re working with strings in no particular order and you need to sort them in reverse alphabetical order.

To approach this problem, you can use sorted(). This built-in function returns a list containing all the items of the input iterable in order. Besides the input iterable, sorted() also accepts a reverse keyword argument. You can set this argument to True if you want the input iterable to be sorted in descending order:

Python
>>> vowels = "eauoi"

>>> # Sort in ascending order
>>> sorted(vowels)
['a', 'e', 'i', 'o', 'u']

>>> # Sort in descending order
>>> sorted(vowels, reverse=True)
['u', 'o', 'i', 'e', 'a']

When you call sorted() with a string as an argument and reverse set to True, you get a list containing the characters of the input string in reverse or descending order. Since sorted() returns a list object, you need a way to turn that list back into a string. Again, you can use .join() just like you did in earlier sections:

Python
>>> vowels = "eauoi"

>>> "".join(sorted(vowels, reverse=True))
'uoiea'

In this code snippet, you call .join() on an empty string, which plays the role of a separator. The argument to .join() is the result of calling sorted() with vowels as an argument and reverse set to True.

You can also take advantage of sorted() to iterate through a string in sorted and reversed order:

Python
>>> for vowel in sorted(vowels, reverse=True):
...     print(vowel)
...
...
u
o
i
e
a

The reverse argument to sorted() allows you to sort iterables, including strings, in descending order. So, if you ever need a string’s characters sorted in reverse alphabetical order, then sorted() is for you.

Conclusion

Reversing and working with strings in reverse order can be a common task in programming. Python provides a set of tools and techniques that can help you perform string reversal quickly and efficiently. In this tutorial, you learned about those tools and techniques and how to take advantage of them in your string processing challenges.

In this tutorial, you learned how to:

  • Quickly build reversed strings through slicing
  • Create reversed copies of existing strings using reversed() and .join()
  • Use iteration and recursion to create reversed strings by hand
  • Loop over your strings in reverse order
  • Sort your strings in descending order using sorted()

Even though this topic might not have many exciting use cases by itself, understanding how to reverse strings can be useful in coding interviews for entry-level positions. You’ll also find that mastering the different ways to reverse a string can help you really conceptualize the immutability of strings in Python, which is a notable feature of the language.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Reversing Strings in Python

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

» More about Leodanis

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics: basics best-practices python

Recommended Video Course: Reversing Strings in Python