How does Reverse String Slicing works in Python?

Viewed 35

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"

1 Answers

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?

Related