0

Just started learning Python. Had to create a function to count a sub-string within a string. Decided to use the count() function of the string module but it doesn't do what I was hoping for.

It seems the count() function will iterate through string and if it does find the sub-string, it will move add to the count but will continue it's iteration at the end of the sub-string.

Below is the code and the test I was running:

def count(substr,theStr):
    counter = 0
    counter = theStr.count(substr, 0, len(theStr))
    return counter



print(count('is', 'Mississippi'))           
# Expected count: 2     pass

print(count('an', 'banana'))                
# Expected count: 2     pass

print(count('ana', 'banana'))           
# Expected count: 2     test failed: count: 1

print(count('nana', 'banana'))          
# Expected count: 1     pass

print(count('nanan', 'banana'))             
# Expected count: 0     pass

print(count('aaa', 'aaaaaa'))           
# Expected count: 5     test failed: count: 2
user1823
  • 1,111
  • 6
  • 19
Mike Van
  • 21
  • 1
  • 1
  • 4

1 Answers1

0

Try taking individual sub strings of the length of the desired string, and checking them:

def count(sub, whole):
    total = 0
    for i in range(0, len(whole)-len(sub)+1):
            if sub == whole[i:i+len(sub)]:
                    total+=1
    return total

>>> print(count('is', 'Mississippi'))           
2
>>> # Expected count: 2     pass
... 
>>> print(count('an', 'banana'))                
2
>>> # Expected count: 2     pass
... 
>>> print(count('ana', 'banana'))           
2
>>> # Expected count: 2     pass
... 
>>> print(count('nana', 'banana'))          
1
>>> # Expected count: 1     pass
... 
>>> print(count('nanan', 'banana'))             
0
>>> # Expected count: 0     pass
... 
>>> print(count('aaa', 'aaaaaa'))           
4
>>> # Expected count: 4     pass
... 
user1823
  • 1,111
  • 6
  • 19