Indexes

Let's look at just a couple more things you can do with variables.

Remember when we were learning about strings, and we talked about indexes? An index is the position of a character in a string. Well, if a variable has a value that's a string, we can get an index from it as well.

Let's go ahead and try this first example. Create a variable named fruit :

>>> fruit = "watermelon"

This variable has the value "watermelon", which is a string. Let's find the letter at the index of 2 for that string.

>>> fruit[2]

When you hit Enter, did you get the character you were expecting?

Here's one more easy example. We've already seen a few ways we can use variables to do math. Well here's one more way - we can use a variable inside those square brackets to calculate an index number.

Go ahead and type this example - create a variable mynumber , then use it to get an index from the fruit variable:

>>> mynumber = 3

>>> fruit[mynumber - 2]

Answers

>>> fruit = "watermelon"

>>> fruit[2]

't'

>>> mynumber = 3

>>> fruit[mynumber - 2]

'a'