将用户输入作为字符串并打印变量 Python

Taking user input as string and printing a variable Python

我试图获取用户输入,然后将该输入转换为变量以打印出列表。

food_list = ["Rice", "l2", "l3"]
Rice = []
l2 = []
l3 = []
answer = input("What item would you like to see from the list")
if answer in food_list:
      print("answer")

我希望输出是打印 Rice 列表,而不是像以前那样只是字符串“Rice”。输入将把它作为一个字符串,但我想将输入转换为列表变量。

Python 的 in 关键字功能强大,但它只检查列表成员。

你想要这样的东西:

food_list = ["Rice", "Cookies"]
answer = input("What item would you like to see from the list")

# if the food is not in the list, then we can exit early
if answer not in food_list:
  print("Food not found in the list")

# we know it's in the list, now you just filter it.
for food in food_list:
  if food == answer:
    print(food)

编码愉快!

你可以用字典来做到这一点:

~/tests/py $ cat rice.py
food_list ={"Rice":"Rice is nice" }

print("What item would you like to see from the list")
answer = input(": ")
if answer in food_list.keys():
      print(food_list[answer])
~/tests/py $ python rice.py
What item would you like to see from the list
: Rice
Rice is nice