【问题标题】:How I write a function in python that determines whether a word has no vowels? [closed]我如何在python中编写一个函数来确定一个单词是否没有元音? [关闭]
【发布时间】:2017-01-31 17:50:23
【问题描述】:

如何在python中编写一个函数“noVowel”来判断一个单词是否没有元音?

在我的例子中,“y”不是元音。

例如,如果单词类似于“My”,我希望函数返回 True,如果单词类似于“banana”,则返回 false。

【问题讨论】:

标签: python


【解决方案1】:
any(vowel in word for vowel in 'aeiou')

word 是您要搜索的词。

分解:

any 返回 True 如果它检查的任何值是 True 则返回 False 否则

for vowel in 'aeiou'vowel 的值设置为a,然后是e,然后是i,等等。

vowel in word 检查字符串 word 是否包含元音。

如果你不明白为什么会这样,我建议你查看生成器表达式,它们是一个非常有价值的工具。

编辑

糟糕,如果有元音则返回True,否则返回False。换一种方式,你可以

all(vowel not in word for vowel in 'aeiou')

not any(vowel in word for vowel in 'aeiou')

【讨论】:

    【解决方案2】:

    试试这个:

    def noVowel(word):
        vowels = 'aeiou' ## defining the vowels in the English alphabet
        hasVowel= False ## Boolean variable that tells us if there is any vowel
        for i in range(0,len(word)): ## Iterate through the word
            if word[i] in vowels: ## If the char at the current index is a vowel, break out of the loop
                hasVowel = True
                break
            else: ## if not, keep the boolean false
                hasVowel=False
        ## check the boolean, and return accordingly
        if hasVowel: 
            return False
        else:
            return True
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 2022-08-12
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2023-01-05
      • 1970-01-01
      相关资源
      最近更新 更多