Search code examples
pythoncs50indexoutofrangeexception

'String index out of range' error and I don't understand why


I'm trying to take an input, drop the vowels, and print the new phrase.

Code

Here's the code I'm using.

phrase = input("Input: ")
for i in range(len(phrase)):
    if str(phrase[i]) in ["a", "A", "e", "E", "i", "I", "O", "o", "u", "U"]:  # error at this line
        phrase = str(phrase[i]).replace(phrase[i], "")
print(phrase)

Issue

On line 3, I am getting the error:

string index out of range

I don't understand how, since I thought I limited the index to the length of the phrase.

Even if there are better ways to create this script (and I would love any suggestions), I would also really love to know where what I'm doing is going wrong and how to fix it!


Solution

  • I think you don't need i as index or range(len(phrase)) to replace a character or to drop certain character in phrase string, If you're intend to take an input, drop the vowels, and print the new phrase.

    phrase = input("Input: ")
    for i in phrase:
        if i in ["a", "A", "e", "E", "i", "I", "O", "o", "u", "U"]:
            phrase = phrase.replace(i, "")
    print(phrase)