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!
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!
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]