Why is this giving output as 1 and not 2:
string = "ABCDCDC"
print(string.count("CDC"))
Also, since this is not working, how can I get 2 in this case?
Why is this giving output as 1 and not 2:
string = "ABCDCDC"
print(string.count("CDC"))
Also, since this is not working, how can I get 2 in this case?
You could use a regular expression to count overlapping substrings:
import re
string = "ABCDCDC"
print(len(re.findall('(?=CDC)', string))) # 2
Here is an algorithmic solution
string = "ABCDCDC"
sub_string = "CDC"
count = 0
for i in range(len(string)):
if string[i:len(sub_string)+i] == sub_string:
count += 1
print count
import re
print([m.start() for m in re.finditer('(?=CDC)', 'ABCDCDC')])
This should find all potentially overlapping occurences
You can try this simple way:
def overlapping_count(string, seek):
seek_len = len(seek)
return sum(c == seek[0] and string[i:i + seek_len] == seek
for i, c in enumerate(string))
string = "ABCDCDC"
print(overlapping_count(string, "CDC"))