Knowing how to reverse a Python string is basic knowledge you should have as Python developer. This can also apply to other data types.
Python does not provide a built-in function to reverse the characters in a string. To reverse a string in Python you can use the slice operator with the syntax [::-1]. You can also use the reversed() function together with the string join() function.
Let’s go through some examples that show you how to approach this in practice.
How Do You Reverse a String in Python?
I want to give you the solution to the problem first, then we will understand how this solution exactly works.
Open the Python shell and define a Python string:
>>> word = "Python"
To reverse a string in Python you can use the slice operator with the following syntax: [::-1].
>>> print(word) Python >>> print(word[::-1]) nohtyP
Fantastic! Nice and concise!
As you can see the second print statement returns the reversed string.
If you want to make this code reusable you can create a function that given a string returns the reversed string.
>>> def reverse_word(word): ... return word[::-1] ... >>> print(reverse_word("Python")) nohtyP
In the next section we will learn how the expression [::-1] works.
What is the Meaning of [::-1] in Python?
You might be wondering, what does the syntax [::-1] mean?
For example, let’s say I want to select the first three characters of our word, I would use the following…
>>> print(word[0:3]) Pyt
The substring starts at the character with index 0 and ends at the character with index 3 – 1 so 2.
If we omit the first zero in the slice expression the output is the same:
>>> print(word[:3]) Pyt
But, the syntax we have used before for the slice operator is slightly different:
It follows extended syntax for the slice operator:
By default the value of step is 1. Also if you don’t specify any value for begin the Python interpreter will start from the beginning of the string.
And, if you don’t specify a value for end Python will go until the end of the string.
Let’s see what happens if we don’t specify a value for begin and end and we set the step to 1:
>>> print(word) Python >>> print(word[::1]) Python
Python goes through every character of the string from the beginning to the end using a step equal to 1.
The only difference in the expression we have seen before to reverse a string is that we have used a step equal to -1.
When you specify a step equal to -1 in a slice operator the Python interpreter goes through the characters of the string backwards. This explain the output returned by the expression [::-1].
>>> print(word[::-1]) nohtyP
How Do You Reverse a String with a Python While Loop?
We can obtain the same output returned by the slice operator but using a while loop.
This is not something I would necessary use if I had to reverse a string in a real application considering that it requires a lot more lines of code compared to the slice operator.
At the same time knowing how to reverse a Python string with a while loop helps you develop the way you think when you look for a solution to a coding problem.
Here is what we want to do…
Start from the end of our string and go backwards one character at the time using a while loop.
Every character is stored in a new string that at the end will be our original string but reversed.
def reversed_word(word): reversed_word = '' index = len(word) - 1 while index >= 0: reversed_word += word[index] index -= 1 return reversed_word
As you can see we start at the index len(word) -1, basically the last character of our string. And we go backwards as long as the index is greater than or equal to zero.
Note: writing index -= 1 is the same as index = index – 1. So it’s just a more concise way to decrement the index by 1.
Let’s test this code by calling our function:
print(reversed_word("Python")) [output] nohtyP
It works fine!
What Does the reversed() Function Do?
Python also provides a built-in function called reversed().
What does it do? Can we use it to reverse the characters in a string?
According to the official Python documentation this is what the reversed() function does…
So, it returns a reverse iterator.
>>> print(reversed("Greece")) <reversed object at 0x7ff8e0172610>
Here is what we get if we cast the reverse iterator to a list.
>>> print(list(reversed("Greece"))) ['e', 'c', 'e', 'e', 'r', 'G']
One way to use the reversed() function to reverse a Python string is to also use the string join() function.
>>> print(''.join(reversed("Greece"))) eceerG
We are using an empty separator character to concatenate the characters returned by the reverse iterator.
We could also cast the iterator to a list before passing it to the join function.
>>> print(''.join(list(reversed("Greece")))) eceerG
These approaches to solve our problem are all one liners.
In one of the final sections of this tutorial we will analyse which approach is the most performant.
How to Reverse a Unicode String
Unicode is a standard used to represent any characters in any language (and not only, with Unicode you can even represent emojis).
You might want to use Unicode if you have to handle strings in languages other than English.
For example, the following word means ‘Good morning’ in Greek:
Let’s print each letter by using their Unicode representation:
>>> print('\U0000039A') Κ >>> print('\U000003B1') α >>> print('\U000003BB') λ >>> print('\U000003B7') η >>> print('\U000003BC') μ >>> print('\U000003B5') ε >>> print('\U000003C1') ρ >>> print('\U000003B1') α
And now let’s print the full word still using the Unicode representation for each character:
>>> word = '\U0000039A\U000003B1\U000003BB\U000003B7\U000003BC\U000003B5\U000003C1\U000003B1' >>> print(word) Καλημερα
We can reverse the string by using the first approach we have covered in this tutorial (the slice operator).
>>> print(word[::-1]) αρεμηλαΚ
Performance Comparison of Approaches to Reverse a Python String
I would like to confirm which one of the approaches to reverse the characters of a string is the fastest.
To measure the performance of each code implementation we will use the Python timeit module.
Reverse a string using the slice operator
import timeit testfunction = ''' def reversed_word(): return 'hello'[::-1] ''' print(timeit.timeit(testfunction)) [output] 0.054680042
Reverse a string using a while loop
import timeit testfunction = ''' def reversed_word(): word = 'hello' reversed_word = '' index = len(word) - 1 while index >= 0: reversed_word += word[index] index = index - 1 return reversed_word ''' print(timeit.timeit(testfunction)) [output] 0.063328583
Reverse a string using the join() and reversed() functions
import timeit testfunction = ''' def reversed_word(): word = 'hello' return ''.join(reversed(word)) ''' print(timeit.timeit(testfunction)) [output] 0.062542167
Reverse a string using the join(), list() and reversed() functions
import timeit testfunction = ''' def reversed_word(): word = 'hello' return ''.join(list(reversed(word))) ''' print(timeit.timeit(testfunction)) [output] 0.059792666999999994
The fastest implementation is the one using the slice operator.
In this tutorial we have seen that it’s possible to reverse the characters of a string using Python in many different ways.
The most performant implementation uses the slice operator but it’s also possible to use the reversed() function together with the join() and list() functions.
Implementing your own function using a looping construct doesn’t really make sense considering that it wouldn’t be as performant as the slice operator and it would take a lot more lines of code.
I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!