Basics Intermediate Advanced
aialgorithmsapibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnewsnumpyprojectspythonstdlibtestingtoolsweb-devweb-scraping
Recommended Course

Reversing Strings in Python
13m · 5 lessons

Reverse Strings in Python: reversed(), Slicing, and More
Table of Contents
Recommended Course
When you’re using Python strings often in your code, you may face the need to work with them inreverse 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 throughslicing
- Createreversed copies of existing strings using
reversed()and.join() - Useiteration andrecursion to reverse existing strings manually
- Performreverse 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 ofstrings,for andwhile loops, andrecursion.
Free Download:Get a sample chapter from Python Basics: A Practical Introduction to Python 3 to see how you can go from beginner to intermediate in Python with a complete curriculum, up-to-date for Python 3.8.
Reversing Strings With Core Python Tools
Working with Pythonstrings inreverse 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 areimmutable in Python, so reversing a given stringin place isn’t possible. You’ll need to create reversedcopies of your target strings to meet the requirement.
Python provides two straightforward ways to reverse strings. Since strings are sequences, they’reindexable,sliceable, anditerable. These features allow you to useslicing to directly generate a copy of a given string in reverse order. The second option is to use the built-in functionreversed() 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 ofinteger indices known asoffsets. 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:
a_string[start:stop:step]Your offsets arestart,stop, andstep. This expression extracts all the characters fromstart tostop − 1 bystep. 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, whilestop 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.
Note: A slicing operation finishes when it reaches the index equal to or greater thanstop. This means that it never includes the item at that index, if any, in the final slice.
Thestep offset allows you to fine-tune how you extract desired characters from a string while skipping others:
>>>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 sliceletters 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 (:). Withstep equal to2, 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 howstep works with negative values. If you provide a negative value tostep, then the slicing runs backward, meaning from right to left.
For example, if you setstep equal to-1, then you can build a slice that retrieves all the characters in reverse order:
>>>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 tolen(letters) - 1, back to the left end of the string, where the index is0. When you use this trick, you get a copy of the original string in reverse order without affecting the original content ofletters.
Another technique to create a reversed copy of an existing string is to useslice(). The signature of this built-in function is the following:
slice(start,stop,step)This function takes three arguments, with the same meaning of the offsets in the slicing operator, and returns aslice object representing the set of indices that result from callingrange(start, stop, step).
You can useslice() to emulate the slicing[::-1] and reverse your strings quickly. Go ahead and run the following call toslice() inside square brackets:
>>>letters="ABCDEF">>>letters[slice(None,None,-1)]'FEDCBA'PassingNone to the first two arguments ofslice() tells the function that you want to rely on its internal default behavior, which is the same as a standard slicing with no values forstart andstop. In other words, passingNone tostart andstop means that you want a slice from the left end to the right end of the underlying sequence.
Reversing Strings With.join() andreversed()
The second and arguably the most Pythonic approach to reversing strings is to usereversed() along withstr.join(). If you pass a string toreversed(), you get an iterator that yields characters in reverse order:
>>>greeting=reversed("Hello, World!")>>>next(greeting)'!'>>>next(greeting)'d'>>>next(greeting)'l'When you callnext() withgreeting as an argument, you get each character from the right end of the original string.
An important point to note aboutreversed() 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 callingreversed() directly as an argument to.join():
>>>"".join(reversed("Hello, World!"))'!dlroW ,olleH'In this single-line expression, you pass the result of callingreversed() directly as an argument to.join(). As a result, you get a reversed copy of the original input string. This combination ofreversed() 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 andrecursion. The final technique uses a functional programming approach with the help of Python’sreduce() function.
Reversing Strings in a Loop
The first technique you’ll use to reverse a string involves afor 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 asconcatenation.
Note: Using.join() is the recommended approach to concatenate strings in Python. It’s clean, efficient, andPythonic.
Here’s a function that takes a string and reverses it in a loop using concatenation:
>>>defreversed_string(text):...result=""...forcharintext:...result=char+result...returnresult...>>>reversed_string("Hello, World!")'!dlroW ,olleH'In every iteration, the loop takes a subsequent character,char, fromtext and concatenates it with the current content ofresult. Note thatresult initially holds an empty string (""). The new intermediate string is then reassigned toresult. At the end of the loop,result holds a new string as a reversed copy of the original one.
Note: Since Python strings are immutable data types, you should keep in mind that the examples in this section use a wasteful technique. They rely on creating successive intermediate strings only to throw them away in the next iteration.
If you prefer using awhile loop, then here’s what you can do to build a reversed copy of a given string:
>>>defreversed_string(text):...result=""...index=len(text)-1...whileindex>=0:...result+=text[index]...index-=1...returnresult...>>>reversed_string("Hello, World!")'!dlroW ,olleH'Here, you first compute theindex of the last character in the input string by usinglen(). The loop iterates fromindex down to and including0. In every iteration, you use theaugmented assignment operator (+=) to create an intermediate string that concatenates the content ofresult with the corresponding character fromtext. Again, the final result is a new string that results from reversing the input string.
Reversing Strings With Recursion
You can also userecursion to reverse strings. Recursion is when a function calls itself in its own body. To prevent infinite recursion, you should provide abase case that produces a result without calling the function again. The second component is therecursive 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:
>>>defreversed_string(text):...iflen(text)==1:...returntext...returnreversed_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, callsreversed_string() itself. The call uses the slicetext[1:] of the input string as an argument. This slice contains all the characters intext, except for the first one. The next step is to add the result of the recursive call together with the single-character stringtext[:1], which contains the first character oftext.
A significant issue to note in the example above is that if you pass in a long string as an argument toreversed_string(), then you’ll get aRecursionError:
>>>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 objectHitting 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 callinggetrecursionlimit() fromsys. By default, this value is usually1000. You can tweak this limit usingsetrecursionlimit() 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!
Usingreduce() to Reverse Strings
If you prefer using a functional programming approach, you can usereduce() fromfunctools to reverse strings. Python’sreduce() takes afolding 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 ofreduce() to reverse strings:
>>>fromfunctoolsimportreduce>>>defreversed_string(text):...returnreduce(lambdaa,b:b+a,text)...>>>reversed_string("Hello, World!")'!dlroW ,olleH'In this example, thelambda function takes two strings and concatenates them in reverse order. The call toreduce() applies thelambda totext 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 asreverse 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.
Thereversed() Built-in Function
The most readable and Pythonic approach to iterate over a string in reverse order is to usereversed(). 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 ofreversed() 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 withreversed():
>>>greeting="Hello, World!">>>forcharinreversed(greeting):...print(char)...!dlroW,olleH>>>reversed(greeting)<reversed object at 0x7f17aa89e070>Thefor loop in this example is very readable. The name ofreversed() clearly expresses its intent and communicates that the function doesn’t produce anyside effects on the input data. Sincereversed() 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 thea_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:
>>>greeting="Hello, World!">>>forcharingreeting[::-1]:...print(char)...!dlroW,olleH>>>greeting[::-1]'!dlroW ,olleH'In this example, you apply the slicing operator ongreeting 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 usingreversed().
Creating a Custom Reversible String
If you’ve ever tried toreverse a Python list, then you know thatlists have a handy method called.reverse() that reverses the underlying listin 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 mimicslist.reverse(). Here’s how you can do that:
>>>fromcollectionsimportUserString>>>classReversibleString(UserString):...defreverse(self):...self.data=self.data[::-1]...ReversibleString inherits fromUserString, which is a class from thecollections module.UserString is a wrapper around thestr built-in data type. It was specially designed for creating subclasses ofstr.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.
InsideReversibleString, 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 howReversibleString works in practice:
>>>text=ReversibleString("Hello, World!")>>>text'Hello, World!'>>># Reverse the string in place>>>text.reverse()>>>text'!dlroW ,olleH'When you call.reverse() ontext, 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 thattext now holds the original string in reverse order.
SinceUserString provides the same functionality as its superclassstr, you can usereversed() out of the box to perform reverse iteration:
>>>text=ReversibleString("Hello, World!")>>># Support reverse iteration out of the box>>>forcharinreversed(text):...print(char)...!dlroW,olleH>>>text"Hello, World!"Here, you callreversed() withtext as an argument to feed afor loop. This call works as expected and returns the corresponding iterator becauseUserString inherits the required behavior fromstr. Note that callingreversed() 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 usesorted(). This built-in function returns a list containing all the items of the input iterable in order. Besides the input iterable,sorted() also accepts areverse keyword argument. You can set this argument toTrue if you want the input iterable to be sorted in descending order:
>>>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 callsorted() with a string as an argument andreverse set toTrue, you get a list containing the characters of the input string in reverse or descending order. Sincesorted() returns alist 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:
>>>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 callingsorted() withvowels as an argument andreverse set toTrue.
You can also take advantage ofsorted() to iterate through a string in sorted and reversed order:
>>>forvowelinsorted(vowels,reverse=True):...print(vowel)......uoieaThereverse argument tosorted() allows you to sort iterables, including strings, in descending order. So, if you ever need a string’s characters sorted in reverse alphabetical order, thensorted() is for you.
Conclusion
Reversing and working with strings inreverse 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 throughslicing
- Create reversed copies of existing strings using
reversed()and.join() - Useiteration andrecursion 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.
Recommended Course
🐍 Python Tricks 💌
Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

AboutLeodanis Pozo Ramos
Leodanis is a self-taught Python developer, educator, and technical writer with over 10 years of experience.
» More about LeodanisMasterReal-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
MasterReal-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
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 andget answers to common questions in our support portal.
Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!
Keep Learning
Keep reading Real Python by creating a free account or signing in:
Already have an account?Sign-In





