-1
    a='12345'
    print(a[::1]) : index starts with 0

Output : 12345

    print(a[::-1])  : index starts with -1 , 

Output : 54321

Output should be 15432 , index must start as usual with 0

  • Because if a slice with a negative step started with index 0 by default, you wouldn't get anything. – kindall Sep 25 '22 at 22:15
  • No , we will get 154321 or should 15432 – Mohammad Salah Sep 25 '22 at 22:17
  • 1
    You are probably thinking that the behavior under the scenes for your negative slicing is `a[0:len(a)-1:-1]` but it will return an empty string. What is really happening behind is `a[len(a)-1:None:-1]` (end=None -> zero IS included; end=0 -> zero IS NOT included) – Juan Federico Sep 25 '22 at 22:38
  • As your mention a[len(a)-1:None:-1] , I agree this the gives the answer , I think this sclicing is folowing a reverse method as `__radd__` (not this method but its reverse way). and this agrees what I guess in my question , with negative step starting index it will not be 0 . Thank you. – Mohammad Salah Sep 26 '22 at 03:27

1 Answers1

0

Python's indexing operator works as follows:

[start:end:step]

I assume when you ask about starting with 0, you mean the first argument. It's true that to get the first character you would need to do

>>> string = "12345"
>>> string[0]
'1'

But what is being done here is that the step is being modified, because the first two arguments are left empty, so are assigned to default values. A step of 1 just means that each character will be selected in order, so nothing changes. A step of 2 would print every other character:

>>> string[::2]
'135'

and a step of -1 moves through the string backwards and prints it in reverse as you showed.

lordnoob
  • 190
  • 12