gpt4 book ai didi

python - 如何让Python同时识别小写和大写输入?

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:17 25 4
gpt4 key购买 nike

我是 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") :
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 = 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")

关于python - 如何让Python同时识别小写和大写输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12719586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com