[Tutor] "Philosophical" question about string slicing from end of a string
Zachary Ware
zachary.ware+pytut at gmail.com
Mon Nov 24 20:33:39 CET 2014
On Mon, Nov 24, 2014 at 1:06 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> On Mon, Nov 24, 2014 at 12:57 PM, Zachary Ware
> <zachary.ware+pytut at gmail.com> wrote:
> [...]
>>
>> Have I clarified or muddied it for you? :)
>
> Clarified, I believe, if my following statements are correct: I did
> not consider that the behavior was symmetric with positive indices.
> So, index 0 is the "center" relative to which positive and negative
> indices create identical behaviors.
Hmm, either I'm not quite following you, or that's not quite right.
For the purposes of slicing, 0 is positive and slices that have either
all positive or all negative indices behave the same way. Mixing
positive and negative indices is of course possible, but takes a
little bit more thought since you're counting from opposite ends.
Also note that there's no way to get the last member with a negative
second index.
[Received while writing the above]
On Mon, Nov 24, 2014 at 1:16 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> Hmm. There is a flaw in my observed "symmetry" in that str[0:3] and
> str[-3:0] do not behave the same as the latter returns an empty
> string.
Correct. Here's another way to think about negative indices,
particularly for converting between positive and negative indices:
>>> s[-5:-3]
'56'
>>> len(s)-5
5
>>> len(s)-3
7
>>> s[len(s)-5:len(s)-3]
'56'
>>> s[5:7]
'56'
So, when you try to do s[-3:0], you're doing s[len(s)-3:0], which
equates to s[7:0]. Building from my example with the length of the
slice in my previous message, the length of that slice would be 0 - 7,
or -7, which obviously won't work very well! Instead of bailing out
with an error there, Python just gives you the shortest substring it
can, ''.
[*] Btw, I've been using 's' instead of 'str' just because it's good
practice not to shadow builtin names like 'str'.
--
Zach
More information about the Tutor
mailing list