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
4 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

If I want the last character of a string, then since len(string) will return a number one larger than the largest index, I would have to input string[length - 1:]. If I input string[length - 4:], I am asking for 3 more characters - that is, 4 characters in total. If I input string[length - length], I would get the first character, since that character resides in index 0. string[length - the largest index number] would give me the second character in the string. Since the first character is pegged to the zero index but length is pegged to the largest index + 1, if you’re slicing string[a:] and formulating ‘a’ in terms of string length, you get as many characters as you subtract from the length.