I need to find count of substring like 'ACA' in a string like ACACA. I tried count(str)
method but it gave me only 1 instead of 2. How can I find actual number of occurrences in python on these strings?
Asked
Active
Viewed 1,883 times
1

ascripter
- 5,665
- 12
- 45
- 68

Ozan Apaydın
- 33
- 5
1 Answers
3
The documentation for the count
method of strings says:
Return the number of non-overlapping occurrences of substring sub in the range [start, end].
Your substrings overlapped, which is why the count
method did not do what you wanted. You can use the find
method's optional parameter to start at a place other than the string's start to find your count:
string = 'ACACA'
substr = 'ACA'
substr_count = 0
start = 0
while True:
loc = string.find(substr, start)
if loc == -1:
break
substr_count += 1
start = loc + 1
This routine's loop count is the same as the number of occurrences of your sub-string in the string. You could use a simpler routine that checks each location of your string to see if the sub-string is at that location, but that take more loops and would be slower.

Rory Daulton
- 21,934
- 6
- 42
- 50
-
Thank you really so much. I used your code and additionnaly I developed mine thanks to you! – Ozan Apaydın Aug 05 '18 at 00:00