slice with negative stride

Fredrik Lundh fredrik at pythonware.com
Sat Oct 6 09:57:36 EDT 2007


ajcppmod at 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>




More information about the Python-list mailing list