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

发布于 2025-01-10 02:19:38 字数 300 浏览 0 评论 0原文

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

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”。输入将其视为字符串,但我想将输入转换为列表变量。

I was trying to take a user input and then convert that input into a variable to print out a list.

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")

I wanted the output to be to print the Rice list, not just the string "Rice" like it has been. The input will take it as a string but I want to turn the input to the list variable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

平生欢 2025-01-17 02:19:38

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

~/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

You can do this with a dictionary:

~/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
奶茶白久 2025-01-17 02:19:38

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)

快乐编码!

Python's in keyword s powerful, however it only checks list membership.

You want something like this:

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)

Happy coding!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文