[Tutor] "Philosophical" question about string slicing from end of a string

Zachary Ware zachary.ware+pytut at gmail.com
Mon Nov 24 19:57:29 CET 2014


On Mon, Nov 24, 2014 at 12:32 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> Python 2.7.8
> Win7Pro
>
>>>> str = "0123456789"
>>>> str[-1]
> '9'
>>>> str[-3:-1]
> '78'
>>>> str[-3:]
> '789'
>
> I understand that the above is "the way it is" in Python, but I am
> puzzled why the designers did not choose that str[-3:-1] returns
> '789', especially since str[-1] returns '9'. What is the reason for
> choosing Python's actual behavior?

For the same reason as this behavior with positive indices:

>>> s = '0123456789'
>>> s[1]
'1'
>>> s[3]
'3'
>>> s[1:3]
'12'

Here's what you can do with it:

>>> s[-5:-3] + s[-3:-1] == s[-5:-1]
True
>>> len(s[-5:-3]) == -3 - -5
True

Think of slicing as "everything from this index (-3) up to but not
including (:) this index (-1)".

Have I clarified or muddied it for you? :)

Regards,
-- 
Zach


More information about the Tutor mailing list