C = 'Kabansososkabansosos'
I need the number of times the string 'sos'
occurs in C
. I've already used the C.count('sos')
method, but it did not help me.
C = 'Kabansososkabansosos'
I need the number of times the string 'sos'
occurs in C
. I've already used the C.count('sos')
method, but it did not help me.
def count_occurrences(expression,word):
L = len(word)
counts = 0
for i in range(L,len(expression)+1):
if expression[i-L:i]==word:
counts += 1
return counts
count_occurrences('Kabansososkabansosos','sos')
>>> 4
To be explicit, your problem is that you want to count non-overlapping occurrences of the sub-string, which is not what str.count()
does.
First, let's use the powerful re
(regular expression) module instead of str.count()
:
C = 'Kabansososkabansosos'
matches = re.findall(r'sos', C)
n = len(matches)
print(n) # 2
At first sight this seems silly, as it 1) also does not work with over-lapping occurrences and 2) produce a (potential) large list of matches, all of which will just be the str
'sos'
.
However, using the clever trick of the accepted answer here, we can make re.findall()
work with overlapping occurrences:
C = 'Kabansososkabansosos'
matches = re.findall(r'(?=(sos))', C)
n = len(matches)
print(n) # 4
If C
is very large, we would like to avoid the potentially large temporary list
matches
. We can do this by instead using the re.finditer()
function, which returns a generator rather than the list
:
C = 'Kabansososkabansosos'
matches = re.finditer(r'(?=(sos))', C)
n = sum(1 for match in matches)
print(n) # 4
where the sum()
over 1
s simply produce the length of the iterator, i.e. the number of matches.