Why is my list index out of range in this for loop?

  Kiến thức lập trình

I’ve been working on Harvard’s CS50 Python course in my free time and am on Problem Set 2. The problem asks you to write a program that receives user input and then outputs the input but without any values. I am having trouble getting past a “IndexError: list index out of range” error within my for loop that acts to delete the recognized vowels.

Initially, I didn’t take into account that upon one character being deleted, the length of the overall string would then also decrease by 1, but I accounted for that by having my index “i” subtract itself from the value within the vowel array. The program seems to work for about 5 vowels before I receive the error, but having written out my logic on paper I just can’t see where I am going wrong.

Also, feel free to comment on my code in general I am a complete beginner with minor experience in MATLAB.

Any advice is appreciated, thank you!

Code:

text = str(input("Input: ")).strip()

# find positions of vowels

vow_pos = []
vowels = ["A","a","E","e","I","i","O","o","U","u"]
k = 0
for i in range(len(text)):
    for k in range(len(vowels)):
        if text[i].find(vowels[k]) != -1:
            vow_pos.append(i)
        k = k + 1

# delete vowels based on position
for j in range(len(vow_pos)):
    if j > 0:
        vow_pos[j] = vow_pos[j] - j
        text = text.replace(text[vow_pos[j]],"")
    else:
        text = text.replace(text[vow_pos[j]],"")


print("Output: " + str(text))

New contributor

Justin Davis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT