Reputation: 23
Very new to Python.I would like to return the first work from an input string that starts with a vowel. If found return the word, else return an empty string. Have the below code however the else statement doesn't seems to work.
for word in string_list:
if word[0] in ['a','e','i','o','u']:
return word
else:
return ""
Upvotes: 1
Views: 1215
Reputation: 173
return should be used in a function. so,
def checker(word):
if word[0] in ['a','e','i','o','u']:
return word
else:
return ""
checker("isuru")
this works.
Upvotes: 0
Reputation: 902
In your code, the for loop will execute only once if you are using it inside the function because you are just checking the first word and returning from the function. Instead, you can use only if
condition inside the for loop and returning empty string part outside the for loop.
And you also need to check with small and capital letters/vowels. string_list here is the list of strings.
def findFirstWordWithVowel(string_list):
for word in string_list:
if word[0] in "aeiouAEIOU":
return word
return ""
Upvotes: 0
Reputation: 61910
You only return
inside a function, for example:
string_list = ['frst', 'hello', 'and']
def first_with_vowel(words):
vowels = 'aeiou'
for word in words:
if any(vowel == word[0] for vowel in vowels):
return word
return ""
print(first_with_vowel(string_list))
Output
and
To verify if any of the vowels is the first letter of a word you could use any. The function any evals to True
if any of vowels is the first letter of the word.
Also in your code the else
is misplaced, if the first word does not start with a vowel you will return ""
, even if the second does. You can remove the else, and return ""
when the loop is over (like in the example code above), meaning there was no word that started with a vowel.
Upvotes: 4