12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

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.

76 Chapter 8. Strings>>> word = 'banana'>>> index = word.find('a')>>> print index1Inthisexample, we invokefindonwordand pass theletter wearelooking for asaparameter.Actually, thefind method is more general than our function; it can find substrings, not just characters:>>> word.find('na')2Itcan take as asecond argument theindex where itshould start:>>> word.find('na', 3)4And as athirdargument the index where itshould stop:>>> name = 'bob'>>> name.find('b', 1, 2)-1This search failsbecausebdoes not appear intheindex range from1to2(not including2).Exercise 8.7 There is a string method called count that is similar to the function in the previousexercise. Read the documentation of this method and write an invocation that counts the number ofasin'banana'.8.9 Thein operatorThe word in is a boolean operator that takes two strings and returns True if the first appears as asubstringinthesecond:>>> 'a' in 'banana'True>>> 'seed' in 'banana'FalseFor example, thefollowing function printsall thelettersfromword1that alsoappear inword2:def in_both(word1, word2):for letter in word1:if letter in word2:print letterWith well-chosen variable names, <strong>Python</strong> sometimes reads like English. You could read this loop,“for (each) letterin(thefirst)word, if(the) letter(appears) in(thesecond) word, print(the) letter.”Here’s what you get ifyou compare apples and oranges:>>> in_both('apples', 'oranges')aes

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

Saved successfully!

Ooh no, something went wrong!