+ 4

Python: finding the index of the first vowel in a string

I recently wrote a function to accept a string as an argument and find the index location of the first vowel in the string. In my case, the string is a single word. My first attempt was as follows: vowelList = 'aeiouAEIOU' def vowelLocator(word) for c in enumerate(word): if c in vowelList: return word.index(c) However this resulted in an output of None. After some research, my second attempt was: vowelList = 'aeiouAEIOU' def vowelLocator(word) for index, c in enumerate(word): if c in vowelList: return index This time the output was accurate, always returning the index of the first occurrence of any vowel in the word. Can someone explain what causes the first function to not work properly, and why the second one works flawlessly? I've been scratching my head trying to figure out how the two variables (index and c) in the second function work together so well.

10th Nov 2018, 4:28 AM
Josh M.
Josh M. - avatar
2 Respuestas
+ 7
enumerate returns you a tuple (index, element). You cannot compare that to characters in a string. Instead of enumerate you could have just gone through the string directly using "for c in word". In the second version you bind the values in the tuple returned by enumerate to the variables "index" and "c". That time you do compare the character in c to the characters in the string.
10th Nov 2018, 4:39 AM
Leif
Leif - avatar
0
Awesome, thanks for the input! Just changed it to: def vowelLocator(word): for c in word: if c in vowelList: return word.index(c) And it works like a charm. Much appreciated.
10th Nov 2018, 4:48 AM
Josh M.
Josh M. - avatar