如何在Python中将字符串输入用作变量调用? [英] How to use a String Input as a Variable Call In Python?

查看:418
本文介绍了如何在Python中将字符串输入用作变量调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有类似这样的代码,我想根据用户输入获取变量项.例如,用户键入输入添加项目",它应该输出item[0]item[1],但是我不知道该怎么做.

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.

推荐答案

将其分解成小块是最简单的方法,可以在需要添加更多命令时避免失控-尝试解析命令字符串切片会很快变得复杂!相反,请尝试将命令拆分为多个单词,然后将每个单词与您要使用的命令相关联.

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

这篇关于如何在Python中将字符串输入用作变量调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆