slice with negative stride
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
>>>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.
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, 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
>>> mystr='my string'
>>> s.indices(len(mystr)) # start is the end of the string if step is
(8, 3, -1)
>>> s.indices(len(mystr)) # start is the beginning of the string if step is
(0, 3, 1)
More information about the Python-list