-1

I am new to Python and have a problem with Negative Slicing step. So can anyone explain me Negative Slicing Step and my question is why the below code behaving like this,

var1='1a2b3c4d5e6f7g8h9i'
print('1st result',var1[-2:-10:-1]) #Get output
print('2nd result',var1[-2:-10:1])  #No Output
print('3rd result',var1[2:10:-1])   #No Output 
auto_learn
  • 1
  • 1
  • 2

2 Answers2

0

Negative slicing is not but positive slicing with step -1.

slice = slice[start,end,step]

You're not able to get output for print('2nd result',var1[-2:-10:1]) #No Output because step of 1 will make index instance as -1 from -2, which is out the prescribed range.

The same is true for print('3rd result',var1[2:10:-1]) #No Output

You should instead be doing

print('2nd result',var1[-2:-10:-1])
print('3rd result',var1[2:10][::-1])
-1

Instead of this you could also write: print("result",var1 [2:10] + var1[-1]), and same for 3rd result And if you still want to use that way, you could also write down the output.

  • I don't see how that is relevant. The question is specifically about negative step. Offering a different approach is really off-topic here... – Tomerikoo Sep 07 '20 at 11:26