slice with negative stride

Paul Hankin paul.hankin at gmail.com
Sat Oct 6 09:46:56 EDT 2007


On Oct 6, 1:05 pm, ajcpp... at gmail.com wrote:
> I'm really confused about results of slices with negative strides. For
> example
>
> >>mystr = 'my string'
> ...
> Can someone explain to me how mystr[:3:-1] = 'gnirt'?

You've omitted the first number in the slice: python uses a sensible
default for it - in this case the index of the end of the string
because your stride is negative. If your stride was positive, the
sensible default is the start of the string, so mystr[:3:1] means
mystr[0:3:1] as you would expect.

It's explained in the python documentation, http://docs.python.org/lib/typesseq.html
(especially note 5 on that page).

--
Paul Hankin




More information about the Python-list mailing list