在Python中,如何检查句子中每个单词的前两个字母,看它们是否有元音?

2024-10-02 00:43:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的暑期班做作业,一个要求我们做这件事的问题把我难住了。请帮帮我!你知道吗

Below is an image of the question:

下面是我对这个问题的尝试:

def canReleaseHounds(s):

vowel = ('aeiouAEIOU')
index = 0
while index < len(s):
    index = s.find(vowel, index)
    if index == -1:
        break
    print ('Vowel found at ' + index)
    index += 1

打印(canReleaseHounds('that's not nice'))


Tags: oftheimageanindexisdefbelow
1条回答
网友
1楼 · 发布于 2024-10-02 00:43:42

你可以试试这个:

def canReleaseHounds(sentence):
    vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"]

    new_sentence = sentence.split()

   return any([True if i[0] in vowels or i[1] in vowels else False for i in new_sentence]

if canReleaseHounds(sentence):
     print("He can be fired")

else:
    print("He cannot be fired")

函数的作用是:检查是否只有一个元素是“Truthy”语句,这意味着它在python意义上是真的。在这种情况下,for循环遍历句子中的单词,如果第一个或第二个单词是元音,它将在列表中存储True。如果在元音列表中找不到单词中的第一个和第二个字母,那么该列表将存储False。当列表被传递给any()函数时,它将查找True的任何实例。如果在列表中没有找到True,那么它将返回False。但是,如果列表中有True,它将返回True。在您的示例中,如果前两个字母中只有一个元音出现,则会存储True。只有一个true就足以返回true,这意味着Lenny可能会被解雇,因为他只需要先说一个元音就可以让自己陷入“麻烦”。我希望这有帮助!你知道吗

有关Python所有函数的更多信息:

How do Python's any and all functions work?

相关问题 更多 >

    热门问题