0

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.

VChocolate
  • 191
  • 1
  • 1
  • 7

2 Answers2

3

You should use count() function for the string.

>>> "abc hi ho".count("hi")
1
>>> "ABChi hi".count("hi")
2
Laszlowaty
  • 1,295
  • 2
  • 11
  • 19
0

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

inbinder
  • 692
  • 4
  • 11
  • 28