[英]How to use a String Input as a Variable Call In Python?
item =["Item_name","Price"]
stop = input("Enter your message: ")
if stop[:3] == "add":
item2 = stop[4:]
我有一个类似这样的代码,我想根据用户输入获取变量项。 例如,用户输入“添加项目”,应该是 output item[0]
和item[1]
,但我不知道该怎么做。
当您需要添加更多命令时,将其分解为小块是防止其失控的最简单方法 - 尝试使用切片解析命令字符串会很快变得复杂,相反,尝试将命令拆分为单词. 然后将每个单词与你想用它做的事情联系起来。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.