简体   繁体   English

Python代码-使用元音返回字符串中的第一个单词

[英]Python code - return first word in a string with vowel

Very new to Python.I would like to return the first work from an input string that starts with a vowel. Python的新手。我想从以元音开头的输入字符串返回第一个工作。 If found return the word, else return an empty string. 如果找到,则返回单词,否则返回空字符串。 Have the below code however the else statement doesn't seems to work. 有以下代码,但是else语句似乎不起作用。

for word in string_list:
    if word[0] in ['a','e','i','o','u']:
        return word
    else:
        return ""

You only return inside a function, for example: 您只return一个函数内部,例如:

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 . 要验证任何元音是否是单词的第一个字母,可以使用any The function any evals to True if any of vowels is the first letter of the word. 如果元音中的任何一个是单词的第一个字母,则函数evals都等于True

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. 同样在您的代码中, else放错了位置,如果第一个单词不是以元音开头,即使第二个单词都以""开头,您也将返回"" 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. 您可以删除else,并在循环结束时返回"" (如上述示例代码中的代码),这意味着没有单词以元音开头。

return should be used in a function. return应该在函数中使用。 so, 所以,

def checker(word):
    if word[0] in ['a','e','i','o','u']:
         return word
    else:
         return ""

checker("isuru")

this works. 这可行。

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. 在您的代码中,如果在函数内部使用for循环,则for循环将仅执行一次,因为您只是在检查第一个单词并从函数中返回。 Instead, you can use only if condition inside the for loop and returning empty string part outside the for loop. 相反,你可以只使用if条件中的for循环和返回空字符串部分以外的for循环。

And you also need to check with small and capital letters/vowels. 并且您还需要检查小写和大写字母/元音。 string_list here is the list of strings. string_list这是字符串列表。

def findFirstWordWithVowel(string_list):
    for word in string_list:
        if word[0] in "aeiouAEIOU":
            return word
    return ""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM