Try this code:
smthing = "blablabla"
mem = "bl"
count = 0
if (smthing == smthing.lower()):
bkpsmthing = smthing # maybe you'll need it later
while (smthing.find(mem) > -1):
smthing = smthing.replace(mem, '', 1)
count += 1
print count
It uses the fact that str.find returns -1 when not finding anything, or the index to the lowest entry to stop:
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure.
It also uses the fact that str.replace can remove a single entry (the lowest) by using the thrid argument (maxreplace). This way we constantly remove entries we've counted:
... If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
The process can be described like this:
find "bl" in "blablabla" -> found at index 0
replace "bl" in "blablabla" -> gives "ablabla"
find "bl" in "ablabla" -> found at index 1
replace "bl" in "ablabla" -> gives "aabla"
find "bl" in "aabla" -> found at index 2
replace "bl" in "aabla" -> gives "aaa"
find "bl" in "aaa" -> not found, returns -1
stop
To do the same thing withtout the count variable use this simple recursion (amke sure you validate the string is lowercase before using my_count):
def my_count(my_string, my_substring):
if my_string.find(my_substring) > -1:
new_string = my_string.replace(my_substring, '', 1)
return my_count(new_string, my_substring) + 1
return 0
Output:
>>> my_count("blablabla", "bl")
3
The recursion unfolds as follows:
my_count("blablabla", "bl") =
= my_count("ablabla", "bl") + 1 =
= my_count("aabla", "bl") + 1 + 1 =
= my_count("aaa", "bl") + 1 + 1 + 1 =
= 0 + 1 + 1 + 1 = 3