如何在Python中使用“notin”运算符生成函数?

2024-06-27 09:09:47 发布

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

我想编写一个函数,测试每个元音是否出现在其参数中,如果文本包含任何小写元音,则返回False,否则返回True

我的代码如下:

def hasNoVowel(text):
    return ('a' not in text) or ('u' not in text) or ('o' not in text) or ('i' not in text) or ('e' not in text) 
print(hasNoVowel('it is a rainy day'))
print(hasNoVowel('where is the sun?'))
print(hasNoVowel("rhythm"))

然而,我得到的结果是:

True
True
True 

代替:假,假,真

有人能帮我解释一下我做错了什么吗

提前谢谢你


Tags: or函数代码textin文本falsetrue
2条回答

您需要在函数中使用and而不是or。当前,仅当所有五个元音都存在时,函数才会返回False

>>> print(hasNoVowel('she found the sun during a rainy day'))
False

您可以使用any(...)评估条件并缩短代码:

def hasNoVowel(text):
    #return ('a' not in text) or ('u' not in text) or ('o' not in text) or ('i' not in text) or ('e' not in text) 
    return not any([v in text for v in 'aeiou'])
print(hasNoVowel('it is a rainy day'))
print(hasNoVowel('where is the sun?'))
print(hasNoVowel("rhythm"))

输出:

False
False
True

相关问题 更多 >