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"

2
  • Does this answer your question? Understanding slicing Commented Sep 1, 2022 at 6:11
  • print(name[4:-1]) Commented Sep 1, 2022 at 7:47

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.