Python 如何计算字符串模块中子字符串的变化?

Python 如何计算字符串模块中子字符串的变化?,python,string,count,substring,counter,Python,String,Count,Substring,Counter,刚开始学习Python。必须创建一个函数来计算字符串中的子字符串。决定使用字符串模块的count()函数,但它没有达到我的期望 似乎count()函数将遍历字符串,如果它确实找到子字符串,它将移动add到count,但将在子字符串的末尾继续其迭代 下面是我运行的代码和测试: def count(substr,theStr): counter = 0 counter = theStr.count(substr, 0, len(theStr)) return counter

刚开始学习Python。必须创建一个函数来计算字符串中的子字符串。决定使用字符串模块的count()函数,但它没有达到我的期望

似乎count()函数将遍历字符串,如果它确实找到子字符串,它将移动add到count,但将在子字符串的末尾继续其迭代

下面是我运行的代码和测试:

def count(substr,theStr):
    counter = 0
    counter = theStr.count(substr, 0, len(theStr))
    return counter



print(count('is', 'Mississippi'))           
# Expected count: 2     pass

print(count('an', 'banana'))                
# Expected count: 2     pass

print(count('ana', 'banana'))           
# Expected count: 2     test failed: count: 1

print(count('nana', 'banana'))          
# Expected count: 1     pass

print(count('nanan', 'banana'))             
# Expected count: 0     pass

print(count('aaa', 'aaaaaa'))           
# Expected count: 5     test failed: count: 2

尝试获取所需字符串长度的单个子字符串,并检查它们:

def count(sub, whole):
    total = 0
    for i in range(0, len(whole)-len(sub)+1):
            if sub == whole[i:i+len(sub)]:
                    total+=1
    return total

>>> print(count('is', 'Mississippi'))           
2
>>> # Expected count: 2     pass
... 
>>> print(count('an', 'banana'))                
2
>>> # Expected count: 2     pass
... 
>>> print(count('ana', 'banana'))           
2
>>> # Expected count: 2     pass
... 
>>> print(count('nana', 'banana'))          
1
>>> # Expected count: 1     pass
... 
>>> print(count('nanan', 'banana'))             
0
>>> # Expected count: 0     pass
... 
>>> print(count('aaa', 'aaaaaa'))           
4
>>> # Expected count: 4     pass
...