在 Python 中检测元音与辅音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20226110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting Vowels vs Consonants In Python
提问by THE DOCTOR
What silly mistake am I making here that is preventing me from determining that the first letter of user input is a consonant? No matter what I enter, it allows evaluates that the first letter is a vowel.
我在这里犯了什么愚蠢的错误,使我无法确定用户输入的第一个字母是辅音?无论我输入什么,它都允许评估第一个字母是元音。
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
if len(original) > 0 and original.isalpha():
if first == "a" or "e" or "i" or "o" or "u":
print "vowel"
else:
print "consonant"
else:
print "empty"
采纳答案by Ashwini Chaudhary
Change:
改变:
if first == "a" or "e" or "i" or "o" or "u":
to:
到:
if first in ('a', 'e', 'i', 'o', 'u'): #or `if first in 'aeiou'`
first == "a" or "e" or "i" or "o" or "u"is always Truebecause it is evaluated as
first == "a" or "e" or "i" or "o" or "u"总是True因为它被评估为
(first == "a") or ("e") or ("i") or ("o") or ("u"), as an non-empty string is always True so this gets evaluated to True.
(first == "a") or ("e") or ("i") or ("o") or ("u"),因为一个非空字符串总是 True,所以它被评估为 True。
>>> bool('e')
True
回答by aust
Your issue is that first == "a" or "e"is being evaluated as (first == "a") or "e", so you're always going to get 'e', which is a Truestatement, causing "vowel"to be printed. An alternative is to do:
你的问题是first == "a" or "e"被评估为(first == "a") or "e",所以你总是会得到'e',这是一个True声明,导致"vowel"被打印。另一种方法是:
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
if len(original) > 0 and original.isalpha():
if first in 'aeiou':
print "vowel"
else:
print "consonant"
else:
print "empty"
回答by agelber
What you are doing in your ifstatement is checking if first == "a"is true and then if "e"is true, which it always is, so the if statement always evaluates to true.
What you should do instead is:
你在你的if语句中所做的是检查 if 是否first == "a"为真,然后 if"e"为真,它总是如此,所以 if 语句总是评估为真。
你应该做的是:
if first == "a" or first == "e" ...
or better yet:
或者更好:
if first in "aeiou":

