Trying a solution for "Return the total count of string "Emma" appears in the given string: I wrote the following code which works fine:
string = 'Emma is a good developer. Emma is a writer'
x = string.count('Emma')
print (f'Emma appeared {x} times')
However, there is an alternative code (below) that also work but I don't seem to be able to understand how it works. Can you please explain how exactly is the code working: For example why do we need to take range at len(statement -1)
what does the code count += statement[i: i + 4] == 'Emma'
do exactly?:
def count_jhon(statement):
print("Given String: ", statement)
count = 0
for i in range(len(statement) - 1):
count += statement[i: i + 4] == 'Emma'
return count
count = count_jhon("Emma is good developer. Emma is a writer")
print("Emma appeared ", count, "times")