06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7<br />

Strings<br />

7.1 A compound data type<br />

So far we have seen three types: int, float, andstring. Strings are qualitatively<br />

different from the other two because they are made up of smaller pieces—<br />

characters.<br />

Types that comprise smaller pieces are called compound data types. Depending<br />

on what we are doing, we may want <strong>to</strong> treat a compound data type as a single<br />

thing, or we may want <strong>to</strong> access its parts. This ambiguity is useful.<br />

The bracket opera<strong>to</strong>r selects a single character from a string.<br />

>>> fruit = "banana"<br />

>>> letter = fruit[1]<br />

>>> print letter<br />

The expression fruit[1] selects character number 1 from fruit. The variable<br />

letter refers <strong>to</strong> the result. When we display letter, we get a surprise:<br />

a<br />

The first letter of "banana" is not a. Unless you are a computer scientist. In<br />

that case you should think of the expression in brackets as an offset from the<br />

beginning of the string, and the offset of the first letter is zero. So b is the 0th<br />

letter (“zero-eth”) of "banana", a is the 1th letter (“one-eth”), and n is the 2th<br />

(“two-eth”) letter.<br />

To get the first letter of a string, you just put 0, or any expression <strong>with</strong> the value<br />

0, in the brackets:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!