Showing posts with label #extended_slicing. Show all posts
Showing posts with label #extended_slicing. Show all posts

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