[Tutor] "Philosophical" question about string slicing from end of a string
Steven D'Aprano
steve at pearwood.info
Mon Nov 24 23:13:37 CET 2014
On Mon, Nov 24, 2014 at 12:32:27PM -0600, boB Stepp 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?
The slice indexes fall *between* characters, not on them. So the string
"abcdef" will have indexes:
|a|b|c|d|e|f|
0 1 2 3 4 5 6
(Things may not line up perfectly unless you read this will a monospaced
font like Courier.)
Think of slicing as cutting on the lines, so the slice [1:4] cuts just
before "b" and just after "d".
Negative indexes work the same way, just in the opposite direction:
|a|b|c|d|e|f|
-6-5-4-3-2-1 ?
Note that the final line, marked with a question mark, would have been 0
except that 0 is already used for positive slicing.
So the slice [-3:-1] cuts before the "d" and just after "e".
--
Steven
More information about the Tutor
mailing list