AvdM AvdM - 3 years ago 248
Python Question

Vowel indices: Python error "'in <string>' requires string as left operand, not int"

I'm a beginner when it's about Python, and I do not quite understand the following:

I try to print the indices of all the vowels that are in the string:

string = "And now for something completely different"
vowel = "aeiouAEIOU"

for i in range(0, len(string)):
if i in vowel:
print(string[i])


So, the output should be something like this, I think:

[0, 5, 9, 13, 15, 18, 23, 27, 29, 34, 37, 39]


Then I get this error:

"'in <string>' requires string as left operand, not int"


I think I do understand that both variables I try to compare should be strings, but I do not see how 'i' is not a string because it does go by every letter of 'string'.

How do I get rid of this error? Maybe I did more wrong, and that is why this code is not working.

I tried to look at similar questions, but the answers did not fit my question entirely and therefore I still haven't figured it out.

Answer Source

You are trying to check if i, which is an integer, is included in the string vowel.

string = "And now for something completely different"
vowel = "aeiouAEIOU"

for i in range(0, len(string)):
    if string[i] in vowel:  
        print(string[i])

By doing this you will print each character in the string that fulfill the inclusion condition.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download