Question about strings

Hi guys,
If I want to select a character from the string: fruit = “watermelon” using the code: fruit[len(fruit) - 2] why would it select “o” and not “l”?

Because counting starts at 0 in programming.

W a t e r m e l o n
0 1 2 3 4 5 6 7 8 9

len(fruit) returns 10, 10-2 = 8 so you get the value at the 8th index which is ‘o’.

2 Likes

Consider the entire set of indices for the word watermelon

-10 -9 -8 -7 -6 -5 -4 -3 -2 -1    # negative indices
  |  |  |  |  |  |  |  |  |  |
  w  a  t  e  r  m  e  l  o  n 
  |  |  |  |  |  |  |  |  |  |
  0  1  2  3  4  5  6  7  8  9    # positive indices

Since we cannot have two elements with index 0, counting from right to left begins with -1.

Note also that len(string) is redundant given we may use the values directly…

string[len(string) - 2]

is the equivalent of,

string[-2]

once we do the math. If we know we want the second from the end, we can use the literal, without doing any computation.