Cristi Chiticariu
Cristi Chiticariu

Reputation: 21

Python: stuck in indexing vowel

So I am preparing for a midterm exam, and doing exercises from a pdf book, i faced this exercise:

" Write code that for a string prints the indices of all of its vowels (a, e, i, o, and u). This can be done with a for loop or a while loop. "

It's given: s = "And now for something completely different"

I coded that:

for j in s:
    for i in range(len(s)):
         if s[i] == "a" or s[i] =="e" or s[i] == "i" or s[i] == "o" or s[i] == "u":
              print (j[i])

And i get the error: 'string index out of range'

I tried that because I used it in another exercise similar that asked for the index of a common letter between two strings, there worked, but now, I don't understand why doesn't work. I'll appreciate if you could explain me how should I look at the exercise. Thanks!

Upvotes: 1

Views: 322

Answers (2)

Alain T.
Alain T.

Reputation: 42133

In your code s seems to be a list of strings. Each string that you process is going to be in the j variable so your uses of len(s) and s[...] are indexing the list s, not the characters of the string j. Because you were consistent in that mistake up until the last line (print(j[i])) it is on that line that the error is detected but the problem is actually on every other reference to s instead of j

BTW, you don't really need a set. you can just use the in operator on regular strings. For a small number of items, this may give sufficient performance using the basic tools that you've learned so far:

for j in s:
    for i in range(len(j)):
        if j[i] in "aeiou":
            print(i,j[i])

Upvotes: 1

kederrac
kederrac

Reputation: 17322

you can use a set to store the vowel, time complexity to search in a set is O(1)

vowel = {'a', 'e', 'i', 'o', 'u'}

for i, e in enumerate(s):
    if e in vowel:
        print(i)

Upvotes: 2

Related Questions