简体   繁体   English

如果 String s 中没有字符是 Python 中的元音,则返回 True

[英]Return True if no character in String s is a vowel in Python

I've tried looking for answers but none seem to help.我试过寻找答案,但似乎没有任何帮助。 I've done:我弄完了:

def noVowel(s):
    'return True if string s contains no vowel, False otherwise'
    for char in s:
        if char.lower() not in 'aeiou':
            return True
        else:
            return False

No matter the string, it always returns True.无论字符串如何,它始终返回 True。

You've almost got it right, but the problem is, as soon as you see a character that is a non-vowel, you return True right then and there.你几乎猜对了,但问题是,一旦你看到一个非元音字符,你就会立即返回 True 。 You want to return True after you've made sure that all are non-vowel:在确定所有内容都是非元音之后,您想返回 True:

def noVowel(s):
    'return True if string s contains no vowel, False otherwise'
    for char in s:
        if char.lower() in 'aeiou':
            return False
    return True  # We didn't return False yet, so it must be all non-vowel.

It's important to remember that return stops the rest of the function from running, so only return if you're sure the function is done computing.重要的是要记住return阻止函数的其余部分运行,因此只有在您确定函数已完成计算时才返回。 In your case, we can safely return False once we see a vowel, even if we didn't check the whole string.在你的情况下,一旦我们看到一个元音,我们就可以安全地return False ,即使我们没有检查整个字符串。

With any and short circuiting properties:具有any和短路特性:

def noVowel(s):
    return not any(vowel in s.lower() for vowel in "aeiou")

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

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