Suppose I declare a string and if I want to print '-1' index to '5' index; I get an answer which I do not expect. Just wanted to know how the string traverses in this case
>>> str = 'qwerty'
>>> str[-1:5]
''
>>> str[-1:6]
'y'
CodePudding user response:
In Python, slicing returns the elements from the starting index till the ending index MINUS ONE. So, if you print s[-1:5]
, it actually will print from the last index 5 till index 4 (note that this is reverse traversal and until the index step is -1, this is not possible). Hence, you get an empty string.
If you print s[-1:6]
, on the other hand, you are basically accessing the last index 5 and 6-1, which is 5, again. This is equivalent to s[5:6]
, which will return the last character y
.
CodePudding user response:
I've name the string x to avoid the name conflict with str.
x = "qwerty"
The -1 denotes the last index of the string, which is 5. From that can you see why your slice results are what they are.
x[0:-1] -> x[0:5] -> "qwert"
x[-1:5] -> x[5:5] -> ""
x[-1:6] -> x[5:6] -> "y"
The low index is inclusive but the upper index is exclusive. Eg. x[0:0]
gives you no characters, but x[0:1]
gives you the 0th index character.
CodePudding user response:
Short answer
because -1 and 5 are the same place and you are slicing from left to right
note that table while using the two forms of indexing
you may read slicing and extended slicing
long answer to understand how slicing works in python
i=0
j=0
str="qwerty"
str[i:j]
OUTPUT
q
it is just about selecting from i index until before j index
so to select last letter "y"
it can be done using i=5
and j=6
.. note no index of 6 can't be actually used you just specify that you will crop from i=5 and crop only one character 6-5=1
also consider there is third argument while slicing
stra = 'qwerty'
print(stra[5:6:1])
will give the same
y
as you slice with start and end as the same with step of 1 you can select from end to start to revrse it by making
stra = 'qwerty'
print(stra[5:-7:-1])
OUTPUT
ytrewq