>>> st = 'I am a string'
>>> st[::-1]
'gnirts a ma I'
It never occurred to me to use slicing in this way. I'm really disappointed I managed to overlook this ability. However, should I ever run into a situation where I need to reverse the contents of a string in Python, I now know of a nice one liner. :)
It works the same with lists (and tuples and arrays):
>>> lt = ["Bob", "Ash", "Mike"]
>>> lt[::-1]
["Mike", "Ash", "Bob"]
But, if I need to reverse a list, I'll probably just stick with
lt.reverse()
. (Unfortunately, that strings do not have this method.)For a more detailed explanation of why this works, check out the Python documentation on Extended Slices.
'emosewa si nohtyp'[::-1]
ReplyDelete