Slicing and offsets

Fredrik Lundh fredrik at effbot.org
Thu Jan 18 16:37:59 EST 2001


gustabares at my-deja.com wrote:
> I got a newbie question here...
>
> >>> S = "spam"
> >>> S[0]
> 's'
> >>> S[1:]
> 'pam'
> >>>
>
> Why is it that when I slice S it's no longer the 0 offset anymore, but
> now it is 1?

Think character boundaries, not character cells.

    0   1   2   3   4
    | s | p | a | m |

The first character sits between boundary 0 and 1, the
second between 1 and 2, etc.

If you use simple indexing, you're asking for the character
just to the right of boundary 0.  If you're slicing, you'll
get whatever's between the given boundaries.

Hope this helps!

Cheers /F

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->








More information about the Python-list mailing list