0

I would like to write a function that counts all non-overlapping occurences of a substring in a string. This is what I have so far:

def count(substr,theStr):
    count = 0
    for i in range(len(theStr)):
        if theStr[i:i+len(substr)] == substr:           
            count = count + 1
    return count

As one can see, my function only counts occurences of a string, but not non-overlapping occurences. For example, the inputs "ana" and "Banana" would yield a count of 2, even though there is only one non-overlapping instance of "ana" in "Banana". How can I extend my function so that it works correctly?

hurlenko
  • 1,363
  • 2
  • 12
  • 17
Moritz Wolff
  • 436
  • 1
  • 7
  • 16
  • 1
    Does this answer your question? [Count the number occurrences of a character in a string](https://stackoverflow.com/questions/1155617/count-the-number-occurrences-of-a-character-in-a-string) – Hippolippo Feb 18 '20 at 12:36
  • @Moritz, fixed bug in your code. Updated my answer. Please check my answer – drd Feb 18 '20 at 13:10
  • @Hippolippo - no, as i said in my question I want to modify the function I provided. I don't want to use other built-in methods or functions. – Moritz Wolff Feb 18 '20 at 13:32

1 Answers1

5

Python has a build-in function for this:

theStr.count(substr)

PS: Maybe you want to have a look at the Python Style-Guide

sxeros
  • 668
  • 6
  • 21
  • I will definitely check it out. Which part of my code makes you think I should look at the Style-Guide? – Moritz Wolff Feb 18 '20 at 13:33
  • @Moritz Wolff The way you name your params and variables in your code. instead of `substr` it would be `sub_str` or `theStr` would be `the_str`...might wanna look through that And as the edit-history shows, you tend to use `tab` instead of multiple spaces...which can lead to formatting-errors – sxeros Feb 18 '20 at 13:41
  • Thanks for the hint - but to get back to the original post, I'm trying not to use a built-in function or method but to extend the function I already built. – Moritz Wolff Feb 18 '20 at 13:57