首页 > 解决方案 > 识别列表中的单词是否以元音开头

问题描述

我需要确定这些单词是否以元音开头。

year= ["january","february","march","april","may","june","july","august","september","october","november","december"]
vowels = "aeiou"

for month in range(len(year)):
    if month.startswith(vowels):
         if_vowel = "Yes"
    else:
         if_vowel = "No"
print("Does the month of {0} start with a vowel? {1}".format(year[i],if_vowel)

理想情况下,它会打印 Yes 或 No 取决于月份是否以元音开头

标签: pythonfor-loopif-statement

解决方案


for month in year:
    print(f"Does the month of {month} start with a vowel? {'Yes' if month[0] == 'e' else 'No'}")

您可以使用 Python3 的f-String进行更轻松的格式化。然后,在 f-String 中,您可以使用条件表达式,例如如果月份的第一个字母是“e”则返回“Yes”,否则返回“No”。


推荐阅读