Reverse a string using Python slices

by admin on July 23, 2009 · 0 comments

I looked through the Python String Methods page expecting to see a Reverse() function but there isn’t one. Googling further I found plenty of people suggesting using this:

s = s[::-1]

But what the hell is that? Not the most intuitive syntax I’ve ever seen. This is using the Python Slice syntax.

Python can take a slice from a list or a string. The syntax is similar to array accessor in other languages like C, C++ and Pascal – in those languages you could do:

char c = s[3];

And in Python it’s the same – but this has been taken further and that array accessor is now much more powerful. For example:

s = “hello world”
print s[6:11]
>>world

l = [0,1,2,3,4,5,6,7,8,9]
print l[2]
>>2

So it can work like a SubString() function in the first example, like a standard array accessor in the second.

The extended slices add a third parameter, which is the step argument – which basically means it’s the number of elements to jump before retrieving the next element. For example

l = [0,1,2,3,4,5,6,7,8,9]
print l[0:9:2]
>>[0, 2, 4, 6, 8]

l = [0,1,2,3,4,5,6,7,8,9]
print l[::2]
>>[0, 2, 4, 6, 8]

Notice the two different slice syntaxes above giving the same output – [0:9:2] and [::2]. If you leave the first parameter blank it defaults to 0 and if you leave the second blank it defaults to the length of the variable being sliced.

And finally by putting -1 in the step you get the reverse string behaviour

s = “hello world”
print s[::-1]
dlrow olleh

Previous post:

Next post: