python 2.7.6打印字符串中的字符串位置
如何打印列表中字符串的位置 我的剧本是:python 2.7.6打印字符串中的字符串位置,python,python-2.7,Python,Python 2.7,如何打印列表中字符串的位置 我的剧本是: plants = 'apples, beans, carrots , dates , eggplant'.split(', ') UI = raw_input ('Please enter a fruit or vegetable. ') for i in list(plants) 预期结果是: 输入水果或蔬菜的名称:胡萝卜 胡萝卜是清单中的第3项 对不起,应该是: UI是列表中的项目。 假设他们输入日期,则为: 日期是列表中的第四项。您可以使用:
plants = 'apples, beans, carrots , dates , eggplant'.split(', ')
UI = raw_input ('Please enter a fruit or vegetable. ')
for i in list(plants)
预期结果是:
输入水果或蔬菜的名称:胡萝卜
胡萝卜是清单中的第3项
对不起,应该是:
UI是列表中的项目。
假设他们输入日期,则为:
日期是列表中的第四项。您可以使用:
返回值为x的第一项列表中的索引。如果没有此类项目,则为错误
这意味着我的所有输入都不在列表中。请删除逗号前的空格或使用split:plants='苹果、豆类、胡萝卜、枣、茄子'。split(',')@jak10101应该是固定的。这是因为拆分时没有删除空格。如果可以合并前两行,会更漂亮。我的意思是split()+strip():)@S.M.AlMamun是的,的确如此。完成了。你想让我们把你所有的作业都写下来吗?
plants = 'apples, beans, carrots , dates , eggplant'
plants = [x.strip() for x in plants.split(',')] # split and remove spaces in names
UI = raw_input ('Please enter a fruit or vegetable. ')
if UI in plants:
print "%s is item %s in the list" % (UI, plants.index(UI))
else:
print "%s isn't in the list" % UI