简体   繁体   English

在 Python 中打印与字符串同名的变量

[英]Printing a variable with the same name as a string in Python

In my project I have user made variables.在我的项目中,我有用户制作的变量。 What I'm trying to do is print the variable if the user gives a string named the same as the variable.如果用户给出与变量同名的字符串,我想要做的是打印变量。 Here's what I think it would look like:这是我认为的样子:

variable = 123
userInput = input("Enter a variable to print: ")
print(userInput)
# Instead of printing userInput, it will check if userInput is the name of a variable, 
# and print if it is.

The user will input "variable", and will print 123 .用户将输入“变量”,并打印123 Also note that the variables will have their custom names and data.另请注意,变量将具有其自定义名称和数据。 So if the variable name is something different, user entering "variable" won't cause it to be printed.因此,如果变量名称不同,用户输入“变量”不会导致它被打印。

And yes, I know that having user-made variables can be a bad idea.是的,我知道拥有用户制作的变量可能是个坏主意。 I know what I'm doing.我知道我在做什么。

You can access your variables dynamically by their name using globals() :您可以使用globals()按名称动态访问变量:

print(globals().get(userInput,"No such variable"))

You can replace "No such variable" with any other default value in case the variable doesn't exist如果变量不存在,您可以将"No such variable"替换为任何其他默认值

You can create a userspace for each user with their own variables, ie您可以使用自己的变量为每个用户创建一个用户空间,即

def get_userspace(user):
    """ Returns current userspace of user. """
    # Here may be Postgres, Redis or just global userspaces
    global userspaces
    return userspaces.setdefault(user, {})

userspaces = {}
userspace = get_userspace(user)

then place all input of specific user in his/her userspace to not interfere with others and to not redefine locals/globals that can be viable for program execution.然后将特定用户的所有输入放在他/她的用户空间中,以免干扰他人也不重新定义对程序执行可行的本地/全局 An then use your code with little improvements to get variable from that userspace:然后使用您的代码稍加改进即可从该用户空间获取变量:

user_input = input("Enter a variable to print: ")
print(userspace.get(user_input))

Here you go.这里是 go。

variable = 123
userInput = input("Enter a variable to print: ")
print(globals()[userInput])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM