How to use a String Input as a Variable Call In Python?

北城余情 提交于 2020-05-09 17:14:23

问题


item =["Item_name","Price"]
stop = input("Enter your message: ")
if stop[:3] == "add":
  item2 = stop[4:]

I have a code something like this and I want to get the variable item based on a user input. For example, the user types inputs "add item", it should output item[0] and item[1], but I don't know how to do it.


回答1:


Breaking it down into small pieces is the easiest way to keep it from getting out of hand when you need to add more commands -- trying to parse a command string with slices is going to get complicated quickly! Instead, try splitting the command into words, and then associating each word with the thing you want to do with it.

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


来源:https://stackoverflow.com/questions/61334293/how-to-use-a-string-input-as-a-variable-call-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!