Tutorial creates confusion about slices

Antoon Pardon apardon at forel.vub.ac.be
Mon Apr 23 09:31:41 EDT 2007


On 2007-04-23, Rob Wolfe <rw at smsnet.pl> wrote:
>
> Antoon Pardon wrote:
>> The following is part of the explanation on slices in the
>> tutorial:
>>
>> The best way to remember how slices work is to think of the indices as
>> pointing between characters, with the left edge of the first character
>> numbered 0. Then the right edge of the last character of a string of n
>> characters has index n, for example:
>>
>>   +---+---+---+---+---+
>>   | H | e | l | p | A |
>>   +---+---+---+---+---+
>>   0   1   2   3   4   5
>>  -5  -4  -3  -2  -1
>>
>> This is all very well with a simple slice like:
>>
>>   "HelpA"[2:4]    =>     "lp"
>>
>>
>> But it give the wrong idea when using the following extended slice:
>>
>>   "HelpA"[4:2:-1]   =>   "Ap"
>>
>> So this doesn't result in the reverse of the previous expression while
>> the explanation above suggest it does.
>
> Clearly I understand that differently:
>
>>>> "HelpA"[-2:-4:-1]
> 'pl'

This is not about what you understand. This is about what the tutorial
seems to suggest here and whether or not that corresponds with how
python actually works.

Read the explanation and look at the picture. The -2 is to the right
of "l" the -4 is to the left of "e". So the picture IMO suggests
that "HelpA"[-2:-4:-1] would result in "le"

-- 
Antoon Pardon



More information about the Python-list mailing list