newbie string question
Don Low
mt at open2web.com
Thu Jun 20 23:40:04 EDT 2002
> 0 1 2 3 4 5 <-- subscript index
> +---+---+---+---+---+---+
> "| P | y | t | h | o | n |"
> +---+---+---+---+---+---+
> 0 1 2 3 4 5 6 <-- slice index
>
> Your slice went from 2 to 5, so it got only the "tho" part of the string.
> Here's what you got:
>
> +---+---+---+
> | t | h | o |
> +---+---+---+
> 2 3 4 5
>
> Other languages confuse the indices used when slicing things (as in
> the common substring() method) and when subscripting things (when you
> take just a single item, such as pystr[4] which is "o" in the above).
>
> Python avoids up this confusion by realizing they are not the same
> thing. (Of course, this can confuse newcomers who don't realize
> what happened, but at least the pain happens for you only once. :-)
>
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.
--
Thanks,
Mark
More information about the Python-list
mailing list