How to reverse a string in Python?

PythonServer Side ProgrammingProgramming

String slicing and range operators can be used to reverse a string in Python. For example:

>>> 'Hello'[::-1]
‘olleH’
>>>‘Halloween’[::-1]
‘neewollaH’

The [] operator can take 3 numbers separated by colon ‘:’. The first is start index, second is end index and third is the stride. Here we have specified the stride as -1 and left other 2 empty, which means we want to go in reverse direction one at a time from beginning to end.

We can also reverse a string using a more readable but slower approach as follows:

>>> ''.join(reversed('Hello'))
‘olleH’
>>> ''.join(reversed('Halloween'))
'neewollaH'

We need to use join as reversed() returns a list and we need to reconstruct string from it.

raja
Published on 11-Dec-2017 11:29:42
Advertisements