newbie string question
Peter Hansen
peter at engcorp.com
Fri Jun 21 00:41:03 EDT 2002
Don Low wrote:
>
> > 0 1 2 3 4 5 <-- subscript index
> > +---+---+---+---+---+---+
> > "| P | y | t | h | o | n |"
> > +---+---+---+---+---+---+
> > 0 1 2 3 4 5 6 <-- slice index
> >
> So if I understand, pystr[3] refers to the subscript index, but pystr[3:]
> refers to the slice index. pystr[2:5] means slice at slice index 2 and 5,
> not start at subscript index 2 and slice at slice index 5.
>
> I just want to understand this once and for all.
Exactly right. And as Fernando reminded us, negative indexes
can be used as well, but with similar interpretation:
-6 -5 -4 -3 -2 -1 <-- negative subscript index
+---+---+---+---+---+---+
"| P | y | t | h | o | n |"
+---+---+---+---+---+---+
-6 -5 -4 -3 -2 -1 : <-- negative slice index
so pystr[-5:-2] is "yth", pystr[-4:] is "thon",
and pystr[-5] is just "y".
You can start to confuse yourself again, maybe :-), by
combining positive and negative slice indices:
pystr[-5:4]
The two diagrams above make it clear what happens tho. ;-)
-Peter
More information about the Python-list
mailing list