【问题标题】:python showing string index out of rangepython显示字符串索引超出范围
【发布时间】:2020-07-30 09:32:33
【问题描述】:

返回字符串“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] 也能工作

有人可以解决我对此的疑问吗?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

假设我们的 str 是“abcde”。

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

str[n+3] with n 为 4 会要求 python 找到“abcde”的第 7 个字母,瞧,一个索引错误。

【讨论】:

  • 我认为问题在于切片不会给出错误 尽管 超出范围,而简单的索引会 - 对比 str[n:n+2]str[n+3]
  • 是的,你是对的,这也是我的疑问,但无法解释清楚
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    循环 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
    

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      相关资源
      最近更新 更多