slice with negative stride

Mark T nospam at nospam.com
Sat Oct 6 16:01:34 CEST 2007


<ajcppmod at gmail.com> wrote in message 
news:1191672336.230508.50600 at o3g2000hsb.googlegroups.com...
> I'm really confused about results of slices with negative strides. For
> example
>
>>>mystr = 'my string'
>
> I would have then thought of the contents of mystr as:
>
> indices    0 1 2 3 4 5 6 7 8
> content    m y   s t r i n g
>
> with mystr[:3] = 'my '
>
> Can someone explain to me how mystr[:3:-1] = 'gnirt'?
>
> I was expecting the result to be mystr[:3] reversed (' ym') i.e slice
> then reverse or even the first 3 elements of the string after being
> reversed ('gni') i.e. reverse then slice.
>
> Thanks
>
> Andy
>

When the step is negative, a missing start is interpreted as the end of the 
string.  A slice always includes the start index character through, but not 
including, the end index character.  In your example, the end index 
character was mystr[3], so you received the end of the string ('g') down to 
but not including 's', which is 'gnirt'.

To see the indices a slice is using, use the slice object's indices method. 
Given the length of a string, it returns the exact start,stop,step indices 
used:

>>> mystr='my string'
>>> s=slice(None,3,-1)
>>> s.indices(len(mystr))  # start is the end of the string if step is 
>>> negative
(8, 3, -1)
>>> mystr[8],mystr[3]
('g', 's')
>>> mystr[8:3:-1]
'gnirt'
>>> s=slice(None,3,1)
>>> s.indices(len(mystr))  # start is the beginning of the string if step is 
>>> positive
(0, 3, 1)
>>> mystr[0],mystr[3]
('m', 's')
>>> mystr[0:3:1]
'my '

-Mark T





More information about the Python-list mailing list