How does slicing using subtraction from the length work?

I’m having trouble understanding why this is the case:

You could also slice the last several characters of a string using len() :

favorite_fruit[length-4:] ‘erry’

If a variable string10 is 10 letters long. There will be index values 0-9. Therefore why does the following code not return 56789. 10 -4 = 6, moving up from index position 6 we get 5, 6, 7, 8, 9?

string10 = "0123456789"
print(string10[len(string10) - 4 : ])
1 Like

No. The character occupying index position 6 is ‘6’.

string10 = "0123456789"
print(string10.index('6'))

# Output:
6
2 Likes

The way I understand this is that the len() function returns an absolute value or the length of the entire string, which in this case is 10 characters long. Then, you are using the length, which is an absolute 10 and reversing direction by using a minus sign and counting back 4 units on an absolute length, 10. So, going back 4 would be a 7 (i.e. 10, 9, 8, 7). Since we are inside square brackets, that means the index is 7 and the actual character of string10 at index 7 is ‘6’. I once took an Algebra course, and the way the teacher explained the minus sign to me is that it means reverse. She said if you are walking forwards, then the minus sign of that would mean reverse that action, which means go backwards. Then, if you put a minus sign in front of that minus sign, it means the reverse of the reverse, which would be forwards again and so on.

1 Like