你可以这样做:string1= input("Enter a string: ")words= string1.split()for word in words: if(word[0] in ['a', 'A']): print(word)或者使用更短的 if 语句: if(word[0] in 'aA'):
string1= input("Enter a string: ")words= string1.split()for word in words: if(word[0]=='a' or word[0] == 'A'): print(word)你做了word[0] == 'a' or 'A',它总是评估为真。你甚至可以像这样使用列表理解:a_words = [word for word in words if word[0] =='a' or word[0] == 'A']
你的测试写错了。现在它看起来像这样:if(word[0]=='a' or 'A'): print(word)但由于 'A' 不为空,循环基本上是:if(word[0]=='a' or True): print(word)它总是会进入,因为它anything or True是真的。您真正想要的是针对a和进行测试A,如下所示:if(word[0]=='a' or word[0]=='A'): print(word)