0

I'm still very new to Python and confused by the question below.

below is the code:

x = "p"
y = x[:-2]

Why doesn't Python handle x[:-2] as an "out-of-bound" slicing and return "p"? In stead, it returns an empty string.

Thank you!

  • actually it should return **index out of range**, I tested it, and yes, strange output –  Nov 01 '20 at 00:30
  • 2
    No @CYREX it shouldn't. This behavior is consistent with how python treats slicing all built-in sequences. See also: https://stackoverflow.com/questions/9490058/why-does-substring-slicing-with-index-out-of-range-work – Mark Nov 01 '20 at 00:33
  • A simpler example that reproduces this: `'p'[:-2]` also gives '' – smci Nov 01 '20 at 00:33

1 Answers1

0

Edit: Sorry, I misread the question as x[:-1]. I'm leaving my original answer because why not.

Let me break it down.. First, in python, a negative index is equivalent to saying [len(my_string) + i]. I being the negative number. For example:

x="abcdefg"
y=x[-2]
print(y)
# will print "f"

Second, x[:-1] is shorthand for x[0:-1], so this would return the substring between the beginning and the last letter (exclusive)

So the reason that you get an empty string in the case of a string of length one is because x[:-1] is equivalent to x[0:0]

Gabriel G.
  • 11
  • 3