Thursday, 1 May 2014

Strings

A compound data type

So far we have seen five types: intfloatboolNoneType and str. Strings are qualitatively different from the other four 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.

No comments:

Post a Comment

Wildern Pupils if you log onto your school email account you can leave a comment via that ID.