next up previous contents index
Next: top Up: Strings Previous: Strings   Contents   Index

startsection section 1 0mm-3.5ex plus -1ex minus -.2ex0.7ex plus.2exA compound data type

So far we have seen three types: int, float, and string. Strings are qualitatively different from the other two because they are made up of smaller pieces--characters.

Types that comprise smaller pieces are called compound data types. Depending on what we are doing, we may want to treat a compound data type as a single thing, or we may want to access its parts. This ambiguity is useful.

The bracket operator selects a single character from a string.


>>> fruit = "banana"
>>> letter = fruit[1]
>>> print letter

The expression fruit[1] selects character number 1 from fruit. The variable letter refers to the result. When we display letter, we get a surprise:


a

The first letter of "banana" is not a. Unless you are a computer scientist. For perverse reasons, computer scientists always start counting from zero. The 0th letter (``zero-eth'') of "banana" is b. The 1th letter (``one-eth'') is a, and the 2th (``two-eth'') letter is n.

If you want the zero-eth letter of a string, you just put 0, or any expression with the value 0, in the brackets:


>>> letter = fruit[0]
>>> print letter
b

The expression in brackets is called an index. An index specifies a member of an ordered set, in this case the set of characters in the string. The index indicates which one you want, hence the name. It can be any integer expression.


next up previous contents index
Next: top Up: Strings Previous: Strings   Contents   Index
root 2004-05-05