alan.gauld at freenet.co.uk
Wed Mar 22 16:57:30 CET 2006
> It helps to think of the indices as pointing to in between the letters.
> Not to the letters themselves.
Like so, where '|' represents the mark:
'corrupt'[0:] -> '|corrupt'
'corrupt'[1:] -> 'c|orrupt'
So an index of 1 moves the mark one place up.
> Negative indices start from the position shown. There's a bit of asymmetry
> here since foo refers to the first element of the string but foo[-1]
> refers to the last one.
If you take both of your comments above you'll see that its quite
consistent. -1 moves the marker back one place from the end
to between the 2nd last and last chars. (it also helps to think of
the sequence as circular so that zero is between the first and
'corrupt'[-1:] -> 'corrup|t'
returns from the -1 position to the end of the string - which is 't'.
-2 moves the mark back 2 places and so on, so the idea of a mark between
the characters is consistent with both forward and negative indexing.
> I'm wrong) is that the slice operator actually creates a new string and
> doesn't return a piece of the existing string.
Correct and is the canonical way to shallow copy a sequence
Author of the learn to program web tutor
More information about the Tutor