我想编写一个函数,该函数计算字符串中子字符串的所有不重叠发生的次数。这是我到目前为止所拥有的:
def count(substr,theStr):
count = 0
for i in range(len(theStr)):
if theStr[i:i+len(substr)] == substr:
count = count + 1
return count
正如人们看到的那样,我的函数仅计算字符串的出现次数,而不统计不重叠的出现次数。例如,即使在“香蕉”中只有一个“ ana”不重叠的实例,输入“ ana”和“ Banana”也将产生2的计数。如何扩展功能以使其正常工作?