Going Deeper with Strings
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 = fruitThe second statement selects character number 1 from
fruitand assigns it to
The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name).
But you might not get what you expect:
>>> letter 'a'For most people, the first letter of '
a. But for computer scientists, the index is an offset from the beginning of the string, and the offset of the first letter is zero.
>>> letter = fruit >>> letter 'b'So
bis the 0th letter (“zero-eth”) of '
banana', a is the 1th letter (“one-eth”), and n is the 2th letter (“two-eth”). As an index you can use an expression that contains variables and operators:
>>> i = 1 >>> fruit[i] 'a' >>> fruit[i+1] 'n'But the value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5] TypeError: string indices must be integers
Source: Author, Allen B. Downey http://greenteapress.com/thinkpython2/html/thinkpython2009.html
This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.