HomepageTeaching PageResearch PageResources Page

Homework: String Search and Counting

Read sections 8.6 and 8.7 in the book and do the examples.

We could write a find_vowel search function like this:

def find_vowel(string):
    """Returns the index of the first vowel in string."""
    for i in range(len(string)):
        char = string[i]
        if char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u':
            #we've found the first vowel, return the index
            return i
    #after the loop, and no vowels. Return -1 for a failed search.
    return -1
        

The if-condition is really long. There's a way to make this shorter that we'll see later in this chapter. Anyways, try out find_vowel on some strings:

>>> find_vowel("banana cheese sandwich")
1
>>> find_vowel("Kyrgyzstan")
8
>>> find_vowel("fly")
-1