首页 > 代码库 > Find and counter
Find and counter
Find:
In a sense, find is the opposite of the [] operator. Instead of taking an index and extracting the corresponding character, it takes a character and finds the index where that character appears. If the character is not found, the function returns -1.
This pattern of computation – traversing a sequence and returning when we find what we are looking for – is called a search.
Looping and counting
The following program counts the number of times the letter a appears in a string:
This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result – the total number of a’s.
from Thinking in Python