Python 如何将对象转换为用于列表搜索的字符串?
我正在尝试搜索一个仅包含用户输入的字符串对象的列表。如果列表中的对象具有与字符串输入相对应的名称,则代码应打印对象的相关信息并返回 但是,即使我输入了我知道在列表中的项目,输出也是“0”。我需要python将列表中的对象识别为字符串,以便它知道输入何时等于其中一个对象 这是我的代码:Python 如何将对象转换为用于列表搜索的字符串?,python,python-3.x,Python,Python 3.x,我正在尝试搜索一个仅包含用户输入的字符串对象的列表。如果列表中的对象具有与字符串输入相对应的名称,则代码应打印对象的相关信息并返回 但是,即使我输入了我知道在列表中的项目,输出也是“0”。我需要python将列表中的对象识别为字符串,以便它知道输入何时等于其中一个对象 这是我的代码: flavor_input = str.upper(input('What is the flavor of the cake you are looking for? ')) for var in cakeList
flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
if str(var) == flavor_input:
print('The flavor has been found')
print(var)
return var
if var not in cakeList:
print('The cake is not on the list!')
return 0
您正在检查列表中的第一项,然后在for循环中迭代该列表。你的逻辑是错误的
cakeList = ['SPAM', 'HAM']
flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
if str(var) == flavor_input:
print('The flavor has been found')
print(var)
break
else:
print('The cake is not on the list!')
或者更简单地说:
if flavor_input in map(str,cakeList):
print('The flavor has been found')
else:
print('The cake is not on the list!')
我不能写评论,所以,也许试试这个
if str.upper(var) in flavor_input:
可能是var单词不是大写的。而且我认为你可以直接比较它们,没有循环
if flavor_input in cakeList
希望对您有所帮助您能发布您的
cakeList
的示例吗?您提供的哪些输入不应产生0
?cakeList中的对象是什么类型?如果cakeList中的var非
缩进在cakeList中的var的下面,那么我看不出这怎么可能是真的。。。