2012-10-04 31 views
3

我是Python新手。我正在编写一个程序来区分单词是否以元音开头。问题是,该程序只能正确处理大写字母作为输入。例如,如果我提供单词“Apple”作为输入,则结果为True;但是,如果提供单词“apple”作为输入,则结果为False。我如何解决它?如何让Python识别低位和高位输入?

word = input ("Please Enter a word:") 
if (word [1] =="A") : 
    print("The word begins with a vowel") 
elif (word [1] == "E") : 
    print("The word begins with a vowel") 
elif (word [1] == "I") : 
    print("The word begins with a vowel") 
elif (word [1] == "O") : 
    print("The word begins with a vowel") 
elif (word [1] == "U") : 
    print("The word begins with a vowel") 
else: 
    print ("The word do not begin with a vowel") 

回答

4

第一完全转换的字为小写字母(或大写):

word = input("Please Enter a word:").lower() # Or `.upper()` 

此外,为了让你的单词的第一个字母,使用word[0],不word[1]。列表以Python和几乎所有的编程语言为零进行索引。

您还可以通过颇有几分凝结代码:

word = input("Please Enter a word:") 

if word[0].lower() in 'aeiou': 
    print("The word begins with a vowel") 
else: 
    print("The word do not begin with a vowel") 
+1

非常感谢。 – user1718826

+0

'word [0] .lower()'可能会稍微更高效 –

1

你可以比较之前的输入转换为大写。

0

你应该使用:

word[i] in 'AEIOUaeiou' 
2

一般你会在输入使用str.lower()(或str.upper())正常化它。

Python3.3有一个名为str.casefold()新方法,它正常工作对Unicode

+1

哇,我不知道'.casefold()'。这似乎很有用! – Blender

+0

很酷。 TIL casefold! – DSM

0

元音的检查是利用str.startswith它可以接受多个值的元组来完成。 PEP 8 Style Guide for Python Code建议超过字符串的切片使用startswith的一段代码更好的可读性:

使用'.startswith()和'.endswith()而不是字符串的切片来 检查前缀或后缀。

Conditional Expressions用于设置指示单词是否以元音开头的消息。然后我用String Formatting方法来准备消息。另外就像一个英语语法校正的东西,我用“这个词不以元音开头”取代了“这个词不以元音开头”这个句子。

word = input("Please Enter a word:") 
is_vowel = 'does' if word.lower().startswith(tuple('aeiou')) else 'does not' 
print("The word {} begin with a vowel".format(is_vowel)) 
0

1)有许多方法可以做到需要做的,像什么搅拌机说了什么。但是,您要做的是将第一个字母转换为大写,无论输入是上限还是下限。使用'大写'来做到这一点。

2)你还需要使用字[0],而不是字[1]来获得的第一个字母出

word = raw_input("Please Enter a word: ").capitalize() 

if word [0] in "AEIOU" : 
    print("The word begins with a vowel") 
else: 
    print ("The word does not begin with a vowel") 

这将使得首字母大写,其余的仍将作为是。