0

I'm trying to find a fast algorithm for counting how many times a substring is found in a string using Python. I know there are some builtin functions for doing that but they do no serve my propose. For example, the word "ana" appears 2 times in "banana" but the string method count just returns 1. The code I have so far is:

s = "banana"
sub = "ana"
count = 0
for i in range(4):
    if s.startswith(sub):
        count += 1

If some one knows a better way, please let me know.

user24312
  • 73
  • 8

1 Answers1

1

possible this:

s = "banana"
sub = "ana"
count = len(s.split(sub))-1
danielarend
  • 1,379
  • 13
  • 26