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.

7.9 The string module 79<br />

As an exercise, encapsulate this code in a function named<br />

countLetters, and generalize it so that it accepts the string and the<br />

letter as arguments.<br />

As a second exercise, rewrite this function so that instead of traversing<br />

the string, it uses the three-parameter version of find from the<br />

previous.<br />

7.9 The string module<br />

The string module contains useful functions that manipulate strings. As usual,<br />

we have <strong>to</strong> import the module before we can use it:<br />

>>> import string<br />

The string module includes a function named find that does the same thing as<br />

the function we wrote. To call it we have <strong>to</strong> specify the name of the module and<br />

the name of the function using dot notation.<br />

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

>>> index = string.find(fruit, "a")<br />

>>> print index<br />

1<br />

This example demonstrates one of the benefits of modules—they help avoid collisions<br />

between the names of built-in functions and user-defined functions. By using<br />

dot notation we can specify which version of find we want.<br />

Actually, string.find is more general than our version. First, it can find substrings,<br />

not just characters:<br />

>>> string.find("banana", "na")<br />

2<br />

Also, it takes an additional argument that specifies the index it should start at:<br />

>>> string.find("banana", "na", 3)<br />

4<br />

Or it can take two additional arguments that specify a range of indices:<br />

>>> string.find("bob", "b", 1, 2)<br />

-1<br />

In this example, the search fails because the letter b does not appear in the index<br />

range from 1 <strong>to</strong> 2 (not including 2).

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

Saved successfully!

Ooh no, something went wrong!