3. Index Operator: Working with the Characters of a String

The indexing operator, [ ], selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 14 characters are indexed left to right from position 0 to position 13.

index values

It is also the case that the positions are named from right to left using negative numbers where -1 is the rightmost index and so on. Note that the character at index 6 (or -8) in the image above is the space character.

The expression school[3] selects the character at index 3 from school, and creates a new string containing just this one character. The variable a_character refers to the result.

Remember that computer scientists often start counting from zero. The letter at index 0 of "LaunchCode LC101" is L. So at position [3] we have the letter n.

The expression in brackets is called an index. An index specifies a member of an ordered collection. In this case, the collection of characters in the string. The index indicates which character you want. It can be any integer expression so long as it evaluates to a valid index value.

Note that indexing returns a string — Python has no special type for a single character. It is just a string of length 1.

When you are going to be indexing into a string, it is useful to know the length of the string. The len function, when applied to a string, returns the number of characters in a string.

To get the last letter of a string, you might be tempted to try something like this:

That won’t work. It causes the runtime error IndexError: string index out of range. The reason is that there is no letter at index position 6 in "Banana". Since we started counting at zero, the six indexes are numbered 0 to 5. To get the last character, we have to subtract 1 from length. Give it a try in the example above by changing line 3 as follows: last = fruit[sz - 1].

Typically, a Python programmer will access the last character by combining the lines 2 and 3 from above.

last = fruit[len(fruit)-1]

Check your understanding