返回字符串“code”在给定字符串中任何位置出现的次数,除非我们接受任何字母作为“d”,所以“cope”和“cooe”计数
count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2
我的代码
def count_code(str):
count=0
for n in range(len(str)):
if str[n:n+2]=='co' and str[n+3]=='e':
count+=1
return count
我知道正确的代码(只需在第3行添加len(str)-3
就可以了),但我无法理解为什么str[n:n+2]
在没有'-3'和str[n+3]
的情况下可以工作
有人能澄清我对此的怀疑吗
说我们的str是“abcde”
如果len(str)中没有-3,那么n的索引将从0,1,2,3,4开始
n为4的str[n+3]会要求python查找“abcde”的第7个字母,瞧,索引器
这是因为for循环将遍历所有字符串文本,因此当
n
表示最后一个单词时n+1
和n+2
不存在。它将告诉您字符串索引超出范围例如:“aaacodebb”最后一个单词的索引是9。因此,当for循环转到最后一个单词时,
n
=9。但是n+1
=10和n+2
=11索引在您的单词中不存在。所以指数10和11超出了范围loop for是一种简单的方法
相关问题 更多 >
编程相关推荐