如何在Python中将字符串输入用作变量调用?
我有一个类似这样的代码,我想根据用户输入获取变量项。例如,用户输入“添加项目”,它应该输出如何在Python中将字符串输入用作变量调用?,python,variables,input,Python,Variables,Input,我有一个类似这样的代码,我想根据用户输入获取变量项。例如,用户输入“添加项目”,它应该输出项目[0]和项目[1],但是我不知道怎么做。当您需要添加更多命令时,将其分解成小块是防止其失控的最简单的方法——尝试用切片解析命令字符串将很快变得复杂!相反,请尝试将命令拆分为多个单词,然后将每个单词与要使用它执行的操作关联起来 item =["Item_name","Price"] stop = input("Enter your message: ") if stop[:3] == "add": i
项目[0]
和项目[1]
,但是我不知道怎么做。当您需要添加更多命令时,将其分解成小块是防止其失控的最简单的方法——尝试用切片解析命令字符串将很快变得复杂!相反,请尝试将命令拆分为多个单词,然后将每个单词与要使用它执行的操作关联起来
item =["Item_name","Price"]
stop = input("Enter your message: ")
if stop[:3] == "add":
item2 = stop[4:]
请从对话中重复[如何提问]()。另见。
from enum import Enum
from typing import Callable, Dict
class Command(Enum):
"""All the commands the user might input."""
ADD = "add"
# other commands go here
class Parameter(Enum):
"""All the parameters to those commands."""
ITEM = "item"
# other parameters go here
item = ["Item_name","Price"]
def add_func(param: Parameter) -> None:
"""Add a thing."""
if param == Parameter.ITEM:
print(item)
COMMAND_FUNCS: Dict[Command, Callable[[Parameter], None]] = {
"""The functions that implement each command."""
Command.ADD: add_func,
}
# Get the command and parameter from the user,
# and then run that function with that parameter!
[cmd, param] = input("Enter your message: ").split()
COMMAND_FUNCS[Command(cmd)](Parameter(param))