python - count an occurrence of a string in a bigger string -


i looking understand can make code work. learning concept unlock lot in programming understanding. trying count number of times string 'bob' occurs in larger string. here method:

s='azcbobobegghakl'  in range(len(s)):     if (gt[0]+gt[1]+gt[2]) == 'bob':        count += 1        gt.replace(gt[0],'')     else:        gt.replace(gt[0],'')  print count 

how refer string instead of having work integers because of using for in range(len(s))?

try this:

def number_of_occurrences(needle, haystack, overlap=false):     hlen, nlen = len(haystack), len(needle)      if nlen > hlen:         return 0 # no occurrences      n, = 0, 0      while < hlen:         consecutive_matching_chars = 0         j, ch in enumerate(needle):             if (i + j < hlen) , (haystack[i + j] == ch):                 consecutive_matching_chars += 1             else:                 break          if consecutive_matching_chars == nlen:              n += 1              # if don't need overlap, skip 'nlen' characters of 'haystack'             += (not overlap) * nlen # booleans can treated numbers          += 1      return n 

example usage:

haystack = 'bobobobobobobobobob' needle = 'bob'  r = number_of_occurrences(needle, haystack) r = haystack.count(needle)  print(r == r) 

Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -