Using Python 2.7, I was attempting to count the number of occurances of \'bob\' in the phrase \'bobbbobobboobobookobobbobbboj.\' To do this, I wrote the code below:
Here is an implementation based on Brandon's answer to a linked question.
def MIT(full_string, substring):
results = []
sub_len = len(substring)
for i in range(len(full_string)):
# range returns a list of values from 0 to (len(full_string) - 1)
if full_string[i:i+sub_len] == substring:
# this is slice notation;
# it means take characters i up to (but not including) i
# + the length of th substring
results.append(i)
return results
full_string = "bobBOBBobBoj"
lower_substring = "bob"
upper_substring = "BOB"
lower_occurrence_array = MIT(full_string, lower_substring)
upper_occurrence_array = MIT(full_string, upper_substring)
number_of_lower_occurrences = len(lower_occurrence_array)
number_of_upper_occurrences = len(upper_occurrence_array)
number_of_occurrences = number_of_lower_occurrences + number_of_upper_occurrences
print ("Number of times bob occurs is: %s" %number_of_occurrences)
The result is
Number of times bob occurs is: 2
The main gist is already there with Paul's answer but I hope this helps.