I want to make a function that does the same thing as count, without using count. Something like this:
>>> count('mama ma emu a ema ma mamu', 'ma ')
4
>>> count('mama ma emu a ema ma mamu', 'am')
2
How could I acheive this?
I want to make a function that does the same thing as count, without using count. Something like this:
>>> count('mama ma emu a ema ma mamu', 'ma ')
4
>>> count('mama ma emu a ema ma mamu', 'am')
2
How could I acheive this?
I thought I'd add an iterative approach where you loop through the string as it would be easier to understand.
Try this:
def count(string, substring):
count = 0
for i in range(len(string) - len(substring) + 1):
if string[i: i + len(substring)] == substring:
count += 1
return count
Essentially, I'm iterating through the possible values of i, where i is the starting index of each substring which is of the same length as the substring entered. Then, I'm simply checking if each possible substring of the correct length is equivalent to the substring entered. If so, I increment my count by 1.