Ron wrote:
[EMAIL PROTECTED] wrote:

Many people I know ask why Python does slicing the way it does.....

Can anyone /please/ give me a good defense/justification???

I'm referring to why mystring[:4] gives me
elements 0, 1, 2 and 3 but *NOT* mystring[4] (5th element).


> There are actually 4 different ways to slice ....

Where s = 'abcd'
With s[i,j]

Foreword slices index, forward steps
    a,  b,  c,  d
i=  0,  1,  2,  3
j=  1,  2,  3,  4

s[0,4] = 'abcd'
s[1,3] = 'bc'
.......


Minor correction to this. It's what I get for not realizing how late it was.

Where s = 'abcd'
With s[i:j:step]

Positive slice index, (+1 step)
     a,  b,  c,  d
 i=  0,  1,  2,  3
 j=  1,  2,  3,  4

 s[0:4] = 'abcd'
 s[1:3] = 'bc'

Positive slice index, (-1 step)
     a,  b,  c,  d
 i=  0,  1,  2,  3
 j= -5, -4, -3, -2

 s[3:-5:-1] = 'dcba'
 s[2:-4:-1] = 'cb'

Negative slice index, (+1 step)
     a,  b,  c,  d
 i= -4, -3, -2, -1
 j=  1,  2,  3,  4

 s[-4:4] = 'abcd'
 s[-3:3] = 'bc'

Reverse slice index, (-1 step)
     a,  b,  c,  d
 i= -4, -3, -2, -1
 j= -5, -4, -3, -2

 s[-1:-5:-1] = 'dcba'
 s[-2:-4:-1] = 'cb'



Cheers,
Ron_Adam
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to