7.1. A string is a sequence¶
A string is a sequence of characters. You can access the characters one at a time with the bracket operator:
>>> fruit = 'banana' >>> letter = fruit
The second statement extracts the character at index position 1 from the
fruit variable and assigns it to the
The expression in brackets is called an index. The index indicates which character in the sequence you want.
But you might not get what you expect:
For most people, the first letter of “banana” is “b”, not “a”. But in Python, the index of a sequence is equal to its offset from the beginning of the string, and the offset of the first letter is zero.
So “b” is the 0th letter (“zero-th”) of “banana”, “a” is the 1th letter (“one-th”), and “n” is the 2th (“two-th”) letter.
You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get: