1

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?

ascripter
  • 5,665
  • 12
  • 45
  • 68

1 Answers1

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