Count occurrences of a word in string | Python program to count the number of occurrence of a word in the given string ; split the string by spaces in a ; search for pattern in a ; if match found increase count ; Driver code
def countOccurrences ( str , word ) : NEW_LINE INDENT a = str . split ( " ▁ " ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , len ( a ) ) : NEW_LINE INDENT if ( word == a [ i ] ) : NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT str = " GeeksforGeeks ▁ A ▁ computer ▁ science ▁ portal ▁ for ▁ geeks ▁ " NEW_LINE word = " portal " NEW_LINE print ( countOccurrences ( str , word ) ) NEW_LINE