Count number of occurrences of a substring in a string
Solution 1:
string.count(substring)
, like in:
>>> "abcdabcva".count("ab")
2
Update:
As pointed up in the comments, this is the way to do it for non overlapping occurrences. If you need to count overlapping occurrences, you'd better check the answers at: "Python regex find all overlapping matches?", or just check my other answer below.
Solution 2:
s = 'arunununghhjj'
sb = 'nun'
results = 0
sub_len = len(sb)
for i in range(len(s)):
if s[i:i+sub_len] == sb:
results += 1
print results