Return the number of times that the string
"hi" appears anywhere in the given string.
count_hi('abc hi ho') # → 1 count_hi('ABChi hi') # → 2 count_hi('hihi') # → 2
I have this solution with me;
def count_hi(str): return str.count("hi")
But I am looking for a solution using a given hint: Use the
for i in range(len(str)-1): loop to look at each index in the string, except the last. For each
i, extract the string starting at
i and up to but not including
i+2. Check if that string is
"hi", and count how many times that happens.
I even tried this solution, but doesn't pass all the test cases:
def count_hi(str): count = 0 for char in str: if char == 'hi': count += 1 return count