This exercise combines lower, split, a loop, and a counter.
count_word with two parameters: text and word.word appears in text as a whole word, ignoring case.count_word("The cat saw the other cat", "cat") returns 2. count_word("The cat", "THE") returns 1.
Whole word means "cat" does not match inside "concatenate" — splitting the text into words before comparing handles this.
Run your code to see the output, then press Submit.
text and word before comparing.import unittest
class TestCountWord(unittest.TestCase):
def test_two_matches(self):
self.assertEqual(count_word("The cat saw the other cat", "cat"), 2)
def test_case_is_ignored(self):
self.assertEqual(count_word("The cat", "THE"), 1)
def test_substrings_do_not_count(self):
self.assertEqual(count_word("concatenate the strings", "cat"), 0)
def test_no_match_gives_zero(self):
self.assertEqual(count_word("nothing here", "cat"), 0)
def count_word(text, word):
target = word.lower()
count = 0
for candidate in text.lower().split():
if candidate == target:
count += 1
return count
print(count_word("The cat saw the other cat", "cat"))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.