a question about s[i:j] when i is negative

dracula571 dracula571 at gmail.com
Tue Oct 17 02:23:06 EDT 2006


s[i:j] slice of s from i to j         (3), (4)

(3)
If i or j is negative, the index is relative to the end of the string:
len(s) + i or len(s) + j is substituted. But note that -0 is still 0.


(4)
The slice of s from i to j is defined as the sequence of items with
index k such that i <= k < j. If i or j is greater than len(s), use
len(s). If i is omitted or None, use 0. If j is omitted or None, use
len(s). If i is greater than or equal to j, the slice is empty.

i can't follow (3) very well.
for example:k = [1,2,3,4,5]
k[-1:2]=[]
k[-5:2]=[1,2]
but k[-6:2] = [1,2]
why k[-6:2] is [1,2]not [].i do follow (3),to make i positive by
plusing len(k) twice.But the result is not what i expect.why,or did i
misunderstand the rule of (3).




More information about the Python-list mailing list