在python中将字符串转换为变量名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19122345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to variable name in python
提问by Harshitha Palihawadana
I have any string. like 'buffalo',
我有任何字符串。像“水牛”,
x='buffalo'
I want to convert this string to some variable name like,
我想将此字符串转换为某个变量名称,例如,
buffalo=4
not only this example, I want to convert any input string to some variable name. How should I do that (in python)?
不仅仅是这个例子,我想将任何输入字符串转换为某个变量名。我应该怎么做(在python中)?
采纳答案by StefanW
x='buffalo'
exec("%s = %d" % (x,2))
After that you can check it by:
之后,您可以通过以下方式进行检查:
print buffalo
As an output you will see:
2
作为输出,您将看到:
2
回答by phntmasasin
This is the best way, I know of to create dynamic variables in python.
这是最好的方法,我知道在 python 中创建动态变量。
my_dict = {}
x = "Buffalo"
my_dict[x] = 4
I found a similar, but not the same question here Creating dynamically named variables from user input
我在这里发现了一个类似但不一样的问题 从用户输入创建动态命名的变量
回答by DeadChex
You can use a Dictionary to keep track of the keys and values.
您可以使用字典来跟踪键和值。
For instance...
例如...
dictOfStuff = {} ##Make a Dictionary
x = "Buffalo" ##OR it can equal the input of something, up to you.
dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to what ever you like
print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.
A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.
字典与现实生活中的字典非常相似。你有一个词,你有一个定义。您可以查找单词并获得定义。所以在这种情况下,你有“Buffalo”这个词,它的定义是 4。它可以与任何其他词和定义一起使用。只要确保你先把它们放进字典里。