data_garden data_garden - 6 months ago 9
Python Question

How many times a word occurs in a string :: general function

I can count the number of times a given word occur inside a

string
, using the following function:

def countWord(w):

numWord = 0
for i in range(1, len(w)-1):
if w[i-1:i+3] == 'word':
numWord += 1
print 'Number of times "word" occurs is:', numWord


How can I correct the code so it will count the number of ANY given
w
, not using built-in functions?

Answer
def countWord(word, mystring):
"""Count the number of times the string `word` is in string `mystring`"""
    numWord = 0
    for i in range(0, len(mystring)-len(word)):
        if substring[i:i+len(word)] == word:
            numWord += 1
    print 'Number of times the word occurs is:', numWord

Note this is poor style. You probably want the function to return the count, and the calling routine to print the result.