1def count_substring(string, sub_string):
2 count=0 #initialise count variable
3 for i in range(0,len(string)):
4 if string[i:].startswith(sub_string): # basically it traverses from left to right and looks for occurence of substring
5 count+=1 #every time count will increase by 1
6
7 return count
1#(method 1)
2import re
3def count_substring(string,sub_string)
4count = re.findall('(?='+sub_string+')',string)
5return len(count)
6
7# (method 2) lengthy but easier for beginners
8def count_substring(string, sub_string):
9 zero=0
10 astring=string + "@"
11 sub_count=0
12 count=0
13 for i in range (len(astring)-1):
14 if astring[i]==sub_string[0]:
15 for j in range(1,len(sub_string)):
16 if astring[i+j]==sub_string[j]:
17 sub_count+=1
18 elif astring[j+i]=='@':
19 break
20 if sub_count==len(sub_string)-1:
21 count+=1
22 sub_count=0
23 return count
24
25