Kedar Kodgire Kedar is a tech blogger, UI/UX designer and developer, cloud engineer, and machine-learning enthusiast. He's passionate about exploring new technologies and sharing them with everyone.

5 methods to reverse a Python string

4 min read 1195

5 ways to Reverse a Python String

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.

Slicing

This is one of the easiest and shortest ways to reverse a string. Slicing in Python accepts three parameters as mentioned below:

  1. Start index
  2. End index
  3. Step (optional, but we need it in our case)

There are two ways to use this operator using the extended slice syntax or the slice function.

Extended slice

>>> '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.

Using reversed and join together

By using both of these functions together, we can achieve the following result:

We made a custom demo for .
No really. Click here to check it out.

>>> 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.

Loops

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'
  1. Here, we are creating a function reverse, which accepts a string as an input.
  2. Then we initialize an empty string, and it will be used for storing output.
  3. Iterating through each character in the input_string, we add the new_string to that character.
  4. Once the loop is completed, we get the desired result, and we return it.

while loop

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?'
  1. Here, we are creating a function and initializing a new variable, the same as the previous example
  2. Now we take the length of the input string and subtract it by 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]
  3. In the 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 loop
  4. 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
  5. Once the count is less than zero, the while loop gets completed, and we get the result

Recursion

>>> 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.

List 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'

Conclusion

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
  • Using Join along with the inbuilt reversed method, which returns an iterable
  • Working with loops for and while is the most straightforward way to reverse a string
  • Use self-calling functions — recursions to reverse a string
  • Utilizing the inbuilt reverse method 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.

: Full visibility into your web 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.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Kedar Kodgire Kedar is a tech blogger, UI/UX designer and developer, cloud engineer, and machine-learning enthusiast. He's passionate about exploring new technologies and sharing them with everyone.

Leave a Reply