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:
There are two ways to use this operator using the extended slice syntax or the slice
function.
>>> '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.
slice
method>>> 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.
reversed
and join
In this method, we use two inbuilt functions: reversed
and join
.
reversed
>>> for letter in reversed('abc'): ... print(letter) ... c b a
The reversed
method returns the iterator (which allows us to access the elements one by one), which we can access in the reverse order.
join
>>> ''.join(['a','b','c']) 'abc'
The 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.
reversed
and join
togetherBy 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.
for
loop>>> 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'
reverse
, which accepts a string as an input.input_string
, we add the new_string
to that character.while
loopSimilar 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?'
1
because 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]
while
loop, 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 loop1
. We reduce the count because we need to stop once the iteration is over; else, it will cause an infinite loopwhile
loop 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[0] ... >>> 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.
reverse
and join
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:
[::-1]
) are the shortest and easiest way to reverse a string. However, we can also use the slice()
method to make it readableJoin
along with the inbuilt reversed
method, which returns an iterablefor
and while
is the most straightforward way to reverse a stringreverse
method in Python to reverse a list and join itThere 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.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]
One Reply to "5 methods to reverse a Python string"
Good article! I personally like Loops for reversing a string