1

I would like to know how does Reverse String Slicing works. For example

name = 'Python'
print(name[4:1])

This code wouldn't give me any result, not even any error. What is actually happening here?

But if I write

print(name[4:1:-1])

It will give the result as "oht"

Manas
  • 13
  • 3

1 Answers1

0

1st example is not giving you any result, because you start off with index 4 and you want to go to index 1 (0, because 1 is excluded) - which is kind of impossible. Default step is 1.

2nd example starts from index 4, ends on index 1, which is excluded. Step in this example is -1, that is why the result is 'oht'.

index of 'Python':
0 1 2 3 4 5
P y t h o n

# 1 is excluded

Python slicing works that way:

name = 'Python'
print(name[start_from_index:go_to_index:step_of_slicing])

is that clear for you?

Bartosz
  • 26
  • 1
  • 4
  • Oh ok so the 1st code is just not how the python works, it can't go back with a step of +1. I get it, but why it's still not giving me an error? – Manas Sep 01 '22 at 06:05
  • @Manas read this: https://stackoverflow.com/questions/509211/understanding-slicing – Bartosz Sep 01 '22 at 07:21