473,231 Members | 1,863 Online

# slice with negative stride

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

Oct 6 '07 #1
2 3853

<aj******@gmail.comwrote in message
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
Oct 6 '07 #2
aj******@gmail.com wrote:
>>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'?
A slice [i:j:k] includes the first index (i) but *not* the last index
(j). Since you're stepping backwards, the slice will start at the end
of the string (i=len(mystr)-1=8) and stop when it reaches j=3.
>>mystr[8]
'g'
>>mystr[7]
'n'
>>mystr[6]
'i'
>>mystr[5]
'r'
>>mystr[4]
't'

</F>

Oct 6 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.