newbie string question

Mike C. Fletcher mcfletch at
Thu Jun 20 23:24:19 EDT 2002

Think of the indices as pointing between the characters. 0 is before the 
first character, len(sequence) is just after the last character, like so.

[ a,  b,  c,  d,  e,  f,  g  ]
  0   1   2   3   4   5   6   7
-7  -6  -5  -4  -3  -2  -1

Asking for a single index gives you the index after the pointer, as if 
you were saying "move to pointer position 5, then read a single item 
(moving forward)".  Asking for a negative index just sets that index = 
len(sequence)+index and does the same thing as normal.

Asking for everything between two pointers/indices (slicing) starts from 
one pointer, and reads all the items up to the end pointer (which is 
sitting just before the character you'd get by asking for pystr[end]). 
If your end-pointer is before or equal to the beginning pointer, it's 
not going to read anything (there's nothing between the pointers moving 
in the forward direction).

So, in the example above,
     0:2  -> a,b
     0:0  ->
     2:3  -> c
     4:-1 -> e,f
     4:-3 ->
     4:-4 ->


PS: Apologies to Tim Peters for mangling his explanation, it's been a 
long time since I've read it.

Don Low wrote:
> There's probably a very simple explanation, but I can't see it for now, so
> bear with me.
>>>>pystr = 'Python'
>>>>pystr = [5]
> 'n'
>>>>pystr [2:5]
> 'tho'
> The question is, why isn't pystr [2:5] 'thon' instead of 'tho'. Could
> somebody explain?

   Mike C. Fletcher

More information about the Python-list mailing list