python - 使用嵌套循环的反元音在 python2 中具有索引错误

标签 python indexing error-handling

我正在做 anti_vowel 函数,它基本上从输入中取出所有元音,并且我在那里有一些错误。 下面是我的代码

def anti_vowel(text):
  vowel="aeiouAEIOU"
  for i in range(len(text)-1):
    for h in range(len(vowel)-1):
      if text[i]==vowel[h]:
        text=text.replace(text[i],"")

  return text      



print anti_vowel("HELLO")

如果我输入“HELLO”,它将成功打印“HLL”。但是如果我将输入更改为“Hey Look Words!”, 它显示错误 IndexError:字符串索引超出范围。如果有人能帮助我解决这个问题,我将非常感激。

最佳答案

您遇到的问题是,.replace() 替换了文本中出现的所有实例。因此,当调用 .replace("o","") 时,您将替换句子中的所有“o”,这会使您的句子更短。因此会发生 IndexError

看看这个:

def anti_vowel(text):
  vowel="aeiouAEIOU"
  for i in range(len(text)-1):
    for h in range(len(vowel)-1):
      print(i,h, text)
      if text[i]==vowel[h]:
        text=text.replace(text[i],"")

  return text      

print(anti_vowel("Heel!"))

输出:

0 0 Heel!
0 1 Heel!
0 2 Heel!
0 3 Heel!
0 4 Heel!
0 5 Heel!
0 6 Heel!
0 7 Heel!
0 8 Heel!
1 0 Heel!
1 1 Heel!
1 2 Hl!
1 3 Hl!
1 4 Hl!
1 5 Hl!
1 6 Hl!
1 7 Hl!
1 8 Hl!
2 0 Hl!
2 1 Hl!
2 2 Hl!
2 3 Hl!
2 4 Hl!
2 5 Hl!
2 6 Hl!
2 7 Hl!
2 8 Hl!
3 0 Hl!

这就是IndexError发生的时候。正如您所看到的,当尝试替换第一个“e”时,所有“e”都会被替换。

我在另一篇 SO 帖子中标记了您的问题,其中显示了如何成功执行此类操作。

关于python - 使用嵌套循环的反元音在 python2 中具有索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58915402/

相关文章:

python - Flask中的路径路由

Python for 循环时间差异

c++ - 来自 vector C++ 中字节表示的 Int

php - 打破 Wordpress post 循环并继续它

javascript - 错误 'getaddrinfo EAI_AGAIN' 的原因是什么?

c++ - 未处理的异常 - 如何解决它,C++

python - 将 int 分配给 pandas 列表列中的字符串

python - 如何在Python中替换unicode汉字?

mysql将索引压入内存

angular - 单击按钮时处理 Angular 错误