擅长:python、mysql、java
<p>修复代码:</p>
<pre><code>def test(N):
s = 'qed'
count = 0
for i in range(len(N)-2):
if N[i:i+3] == s:
count += 1
return count
>>> test('qedmlqedlolqed')
3
</code></pre>
<p>或者更一般地说:</p>
<pre><code>def test(N, s):
count = 0
if s:
for i in range(len(N)-len(s)+1):
if N[i:i+len(s)] == s:
count += 1
return count
>>> test('qedmlqedlolqed', 'qed')
3
>>> test('qedmlqedlolqed', 'ed')
3
>>> test('qedmlqedlolqed', 'd')
3
>>> test('qedmlqedlolqed', '')
0
>>> test('qedmlqedlolqed', 'lol')
1
>>> test('qedmlqedlolqed', 'rofl')
0
</code></pre>
<hr/>
<p>或者,更简单的方法是使用<code>str.count()</code>:</p>
<pre><code>>>> 'qedmlqedlolqed'.count('qed')
3
</code></pre>
<p>'</p>