VChocolate VChocolate - 1 year ago 46
Python Question

Return a number of times of a specific string in python

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

My code is below:

def count_hi(str):
sum = 0
count = 1
if "hi" in str:
sum = sum + count
count = 1 + count
return count and sum

I'm trying to do it with character slicing. So I can test if there is a "h" and "i" in a word and counting the combination of "h" and "i" to make "hi" . So "hi" could be at the beginner, middle, and/or at the end of a bunch of words or letters and/ or by itself.


You should use count() function for the string.

>>> "abc hi ho".count("hi")
>>> "ABChi hi".count("hi")