Monday, July 24, 2017

6 different ways to reverse a string in Python

A lot of interviewers seem to have a fascination for this often asked question :

"How to reverse a string in Python ?"

There are of course, many possible answers for this. Here are some that might come in handy for your understanding and learning.

1. Old School while loop method

>>> x = "hello"
>>> idx = len(x)
>>> rev = list()
>>> while idx > 0:
...         rev.append( x[idx-1] )
...         idx -= 1
...
>>> print ''.join(rev)
olleh

2. Using Python's reversed function with a for loop




This helps to eliminate the "idx" variable from above solution
>>> x = "hello"
>>> rev = list()
>>> for ch in reversed(x):
...         rev.append( ch )
...
>>> print ''.join(rev)
olleh

3. Using Python's reversed function in a List Comprehension


This is pretty much a short form of the above solution.
>>> x = "hello"
>>> print ''.join( [ ch for ch in reversed(x) ] )
olleh

4. Using Python's reversed function with join


Python's reversed() function returns an iterable object. And string method join() expects an iterable data type as input. We can combine these two to get an easier solution.
>>> x = "hello"
>>> print ''.join( reversed(x) )
olleh

5. Using a list to reverse a string

>>> x = "hello"
>>> chs = list(x)
>>> chs.reverse() # operation is done in-place
>>> print ''.join(chs)
olleh

6. Using Python's extended sliced syntax


This is the most effecient and Pythonic way of achieving this result. The other methods mentioned above, though not so efficient are more readable. But, once you get the hang of using string slicing, you will agree that, the extended slice syntax is quite readable as well.
>>> x = "hello"
>>> print x[::-1]
olleh


Understanding how extended slicing works is a topic in itself. That will require a fairly good understanding of slicing. You will find it nothing less than surprising, to say the least.

No comments:

Post a Comment