0

In the following example:

s = '1234567'
s[-2:-5] == ''

I am confused as to why the substring wouldn't be '654' and is instead the empty string.

1 Answer 1

3

You forgot to include the step parameter in the slice. It is 1 by default; therefore, by default, if start is greater than stop, the slice will be empty. Specify the step as -1:

s = '1234567'
print(s[-2:-5:-1])
# 654

In essence, it will start at index -2 at go backwards to index -5 instead of trying to go forward to index -5, which is impossible.

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

Comments

Your Answer

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