1

I'm doing the anti_vowel function, which basically takes out all of the vowels from the input,and I have some bugs there. Here is my code down below

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")

If I input "HELLO",it will success to print"HLL".But if I changed my input to"Hey look Words!", it shows error IndexError: string index out of range.I am very grateful if someone can help me solving this problem.

jeffery
  • 13
  • 2
  • Does this answer your question? [How can I do multiple substitutions using regex in python?](https://stackoverflow.com/questions/15175142/how-can-i-do-multiple-substitutions-using-regex-in-python) – Nils Nov 18 '19 at 13:15
  • You change the collection you are iterating over. It will fail if the second vowel is before the last character. Try the input "EEL" This may be better: https://stackoverflow.com/a/3939381/1766544 – Kenny Ostrom Nov 18 '19 at 13:20
  • The whole function body could be reduced to `return ''.join(character for character in text if character not in 'aeiouAEIOU')`. If you want to learn Python then try to understand this code. – Matthias Nov 18 '19 at 13:39
  • @Matthias Thanks a lot,it is such a simple code – jeffery Nov 18 '19 at 19:53

1 Answers1

0

The issue you are having is, that .replace() replaces all instances that occur in your text. Therefore when calling .replace("o","") you are replacing all "o"s in your sentence, which then makes your sentence shorter. So an IndexError occurs.

Take a look at this:

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!"))

Output:

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!

That's when the IndexError occurs. As you can see when trying to replace the first 'e' all 'e's are replaced.

I flagged your question with another SO-post where it is shown how you can do such an operation successfully.

Nils
  • 910
  • 8
  • 30