python显示字符串索引超出范围

2024-09-30 04:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

返回字符串“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]的情况下可以工作

有人能澄清我对此的怀疑吗


Tags: 字符串代码lendefcount字母code次数
3条回答

说我们的str是“abcde”

如果len(str)中没有-3,那么n的索引将从0,1,2,3,4开始

n为4的str[n+3]会要求python查找“abcde”的第7个字母,瞧,索引器

这是因为for循环将遍历所有字符串文本,因此当n表示最后一个单词时n+1n+2不存在。它将告诉您字符串索引超出范围

例如:“aaacodebb”最后一个单词的索引是9。因此,当for循环转到最后一个单词时,n=9。但是n+1=10和n+2=11索引在您的单词中不存在。所以指数10和11超出了范围

loop for是一种简单的方法

def count_code(str):
  count = 0
  for i in range(len(str)-3): 
# -3 is because when i reach the last word, i+1 and i+2
# will be not existing. that give you out of range error.  
      if str[i:i+2] == 'co' and str[i+3] == 'e':
      count +=1
  return count

相关问题 更多 >

    热门问题