Monday, August 9, 2010

Reversing a string in Python

I recently purchased a new Python book, Python for Bioinformatics, by James Kinser. As I was skimming through the introductory portion of the book I came across a rather interesting piece of Python code related to slicing:


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

1 comment: