如何让Python同时识别小写和大写输入?
我是Python新手。我正在写一个程序来区分一个单词是否以元音开头。问题是,该程序只能正确处理大写字母作为输入。例如,如果我提供单词“Apple”作为输入,结果是如何让Python同时识别小写和大写输入?,python,uppercase,lowercase,Python,Uppercase,Lowercase,我是Python新手。我正在写一个程序来区分一个单词是否以元音开头。问题是,该程序只能正确处理大写字母作为输入。例如,如果我提供单词“Apple”作为输入,结果是True;但是,如果提供单词“apple”作为输入,则结果为False。我怎么修理它 word = input ("Please Enter a word:") if (word [1] =="A") : print("The word begins with a vowel") elif (word [1] == "E") :
True
;但是,如果提供单词“apple”作为输入,则结果为False
。我怎么修理它
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")
首先将单词完全转换为小写(或大写): 此外,要获取单词的第一个字母,请使用
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")
您可以在比较之前将输入转换为大写。您应该使用:
word[i] in 'AEIOUaeiou'
通常,您会对输入使用
str.lower()
(或str.upper()
)将其正常化
Python3.3有一个新方法,名为,它适用于unicode元音检查是使用它来完成的,它可以接受多个值的元组。建议使用startswith和over string切片,以提高代码的可读性: 使用“”StartWith()和“”endswith()代替字符串切片 检查前缀或后缀 用于设置指示单词是否以元音开头的消息。然后我用这个方法来准备信息。同样,作为一项英语语法修正,我将“单词不以元音开头”替换为“单词不以元音开头”
word = input("Please Enter a word: ").upper()
if word [0] in "AEIOU" :
print("The word begins with a vowel")
else:
print ("The word does not begin with a vowel")
这将使第一个字母大写,其余字母保持原样。
word[0]。lower()
可能会稍微有效一点。W,我不知道.casefold()
。它似乎很有用!
word = input("Please Enter a word: ").upper()
if word [0] in "AEIOU" :
print("The word begins with a vowel")
else:
print ("The word does not begin with a vowel")