0

I am doing an exercise where for a string, you print the index of all of its vowels. I was able to do it with enumerate() but still don't understand why the below did not work:

s = "And now for something completely different"
vowels = ["A", "a", "E", "e", "I", "i", "O", "o", "U", "u"]

for char in s:
    if char in vowels:
        print(s.index(char))
    else:
        continue

This outputs: 0 5 5 5 15 18 5 15 15 18 15 15.

In addition, I noticed that it still outputs the same without the "else" statement: does this mean that I don't explicitly need to state (with "continue") to try the next character if the current one is not in the input string?

What I wanted to achieve can be done as follows:

s = "And now for something completely different"
vowels = ["A", "a", "E", "e", "I", "i", "O", "o", "U", "u"]

for i, char in enumerate(s):
        if char in vowels:
            print(i)

This correctly outputs: 0 5 9 13 15 18 23 27 29 34 37 39.

s1renetta
  • 1
  • 3
  • `index` always gives you the first matching index, no matter how many times you ask it to find the same character in the same string. You can correct for this by slicing the string after each match, but it's *much* easier (and more efficient) to just do the `enumerate` thing that you've already discovered. – Samwise Mar 04 '22 at 20:02
  • re: your `else`, yes. Loops continue until they're either finished or until they're interrupted (by a `break`, `raise`, or `return`). You only need a `continue` if you want to explicitly skip the rest of the current iteration; `continue` at the end of the iteration is always a no-op. – Samwise Mar 04 '22 at 20:03
  • Oh wow that helps, so it just gives me the index of the first "A", then the index of the first "o" for every "o" it encounters, and so on. Thank you, Samwise! Edit: Okay, it has already been closed, problem solved! – s1renetta Mar 04 '22 at 20:09

0 Answers0