data_garden data_garden - 2 years ago 109
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

, 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
, not using built-in functions?

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download