A sequence of characters forms a string in Python. However, in Python, strings are immutable — changing strings doesn’t alter the string, but it creates a new one. Hence there are no inbuilt methods to reverse a string in Python.
Well, don’t worry about it; we have a few workarounds to achieve the task of reversing the string. Let’s look at these methods one by one.
This is one of the easiest and shortest ways to reverse a string. Slicing in Python accepts three parameters as mentioned below:
- Start index
- End index
- Step (optional, but we need it in our case)
There are two ways to use this operator using the extended slice syntax or the
>>> 'raed ,tsop eht ot emocleW'[::-1] 'Welcome to the post, dear.' >>> x = '.gnidaer rof sknahT' >>> x[::-1] 'Thanks for reading.'
In the example above, we haven’t provided any start and end index. By default, the start index is considered
0, the end index as
n-1. We mention step as
-1, which means the string continues the traverse from the end and goes to the beginning providing the desired result. As shown above, we can also assign the string to a variable and perform this operation.
>>> step = -1 >>> stop = None >>> start = None >>> slicing=slice(start, stop, step) >>> '.siht gniyojne era uoy epoh I'[slicing] 'I hope you are enjoying this.'
Here we assign values
-1 to step and
None for a start and stop index. Then, we use the
slice() function, store the object into the variable
slicing, and use it with the string later.
In this method, we use two inbuilt functions:
>>> for letter in reversed('abc'): ... print(letter) ... c b a
reversed method returns the iterator (which allows us to access the elements one by one), which we can access in the reverse order.
>>> ''.join(['a','b','c']) 'abc'
join method takes values from the iterator and sews them into a string. The quotes at the beginning are used to specify a character or a pattern to join the string. We don’t want any pattern; hence we left it blank.
By using both of these functions together, we can achieve the following result:
>>> custom_string = '.flesym ecudortni em teL' >>> ''.join(reversed(custom_string)) 'Let me introduce myself.'
Here we pass the string to the
reversed function and feed the same to the
join function, which provides the required result.
>>> def reverse(input_string): ... new_string = '' ... for character in input_string: ... new_string = character + new_string ... return new_string ...
>>> reverse('radeK si eman yM') 'My name is Kedar'
- Here, we are creating a function
reverse, which accepts a string as an input.
- Then we initialize an empty string, and it will be used for storing output.
- Iterating through each character in the
input_string, we add the
new_stringto that character.
- Once the loop is completed, we get the desired result, and we return it.
Similar actions can be performed using the
while loop. But, first, let’s look at the example:
>>> def w_reverse(input_string): ... new_string = '' ... count = len(input_string) - 1 ... while count >= 0: ... new_string = new_string + input_string[count] ... count = count - 1 ... return new_string >>> w_reverse('?uoy era woH') 'How are you?'
- Here, we are creating a function and initializing a new variable, the same as the previous example
- Now we take the length of the input string and subtract it by
1because the index in Python starts from
0. The action of subtracting can be done in another way as well, i.e.,
new_string = new_string + input_string[count - 1]
- In the
whileloop, we check if the calculated length is greater than or equal to zero. This part should be done carefully because any mistakes can lead a program to an infinite loop
- Next, we add the new string to the iterated character and reduce the count by
1. We reduce the count because we need to stop once the iteration is over; else, it will cause an infinite loop
- Once the count is less than zero, the
whileloop gets completed, and we get the result
>>> def reverse(str): ... if len(str) == 0: # Checking the length of string ... return str ... else: ... return reverse(str[1:]) + str ... >>> reverse('.syaw tnereffid ni gnirts nohtyP a esrever ot elba eb dluohs uoy ,won yB') 'By now, you should be able to reverse a Python string in different ways.'
Recursion is a concept in which the function calls itself. In our case, we are defining a function that takes string input. Firstly we check if the length of the received string is equal to zero; if it is, we return the string. Then, we call the same function and pass the input except for the first character if this condition fails. The result will be joined with the first omitted character.
This function will end only when the length of the input string is zero.
This is the last method that we are going to look at today. Here we convert the input string into the list of characters. Then we use the
reverse method on top of it. Finally, we use the
join method to join the characters of the reversed list:
>>> def list_reverse(input_string): ... input_list = list(input_string) ... input_list.reverse() ... return ''.join(input_list) ... >>> >>> list_reverse('dohtem tsal ehT') 'The last method'
Working with strings and reversing them can be a common task in any programming language. Even though this topic may not have compelling use cases, this knowledge will be helpful for you in your coding interviews.
Here is a summary of the strategies used in this post:
- Extended slices (
[::-1]) are the shortest and easiest way to reverse a string. However, we can also use the
slice()method to make it readable
Joinalong with the inbuilt
reversedmethod, which returns an iterable
- Working with loops
whileis the most straightforward way to reverse a string
- Use self-calling functions — recursions to reverse a string
- Utilizing the inbuilt
reversemethod in Python to reverse a list and join it
There are multiple ways to solve a problem in computer science, but not every solution is efficient. So now that we have seen different ways to reverse a Python string, I encourage you to calculate runtimes for the various ways you learned above. In this way, you get to try each of these methods by yourself, so you get a good hold of it and have the fastest strategy at the end.
Let me know in the comments which one is the fastest.
LogRocket: Full visibility into your web and mobile apps
LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
More great articles from LogRocket:
- Don't miss a moment with The Replay, a curated newsletter from LogRocket
- Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
- Use React's useEffect to optimize your application's performance
- Switch between multiple versions of Node
- Discover how to animate your React app with AnimXYZ
- Explore Tauri, a new framework for building binaries
- Compare NestJS vs. Express.js