Solution 1

def how_many_times(a_string, a_word):
    return a_string.count(a_word)

How many times

Write a function how_many_times that receives a string (like a short sentence text) and a word and returns the number of times that word is repeated in the sentence. Example, given the following sentence:

Courage is not the absence of fear, but rather the judgement that something else is more important than fear
(Ambrose Redmoon)

How many times was the word fear used?

Your how_many_times function will exactly answer that.


phrase = "Python is a great language. I like Python a lot."
how_many_times(phrase, "Python")  # Returns 2

Hint: check special methods of strings.

Test Cases

test none - Run Test

def test_none():
    phrase = "Python is a great language."
    assert how_many_times(phrase, "Ruby") == 0

test only once - Run Test

def test_only_once():
    phrase = "Python is a great language. I like it a lot."
    assert how_many_times(phrase, "Python") == 1

test more than once - Run Test

def test_more_than_once():
    phrase = "Python is a great language. I like Python a lot."
    assert how_many_times(phrase, "Python") == 2
def how_many_times(a_string, a_word): pass