By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,645 Members | 1,065 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,645 IT Pros & Developers. It's quick & easy.

slice with negative stride

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a

<aj******@gmail.comwrote in message
news:11*********************@o3g2000hsb.googlegrou ps.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
Oct 6 '07 #2

P: n/a
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 discussion thread is closed

Replies have been disabled for this discussion.