将字符串转换为变量nam

2024-04-23 20:30:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有绳子。就像“水牛”

x='buffalo'

我想把这个字符串转换成变量名,比如

buffalo=4 

不仅是这个例子,我还想把任何输入字符串转换成变量名。我应该怎么做(在python中)?


Tags: 字符串例子buffalo绳子水牛
3条回答

这是用python创建动态变量的最佳方法。

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

我在这里发现了一个相似但不相同的问题 Creating dynamically named variables from user input

[根据马蒂金的建议编辑]

x='buffalo'    
exec("%s = %d" % (x,2))

之后,您可以通过以下方式进行检查:

print buffalo

作为输出,您将看到: 2

您可以使用字典来跟踪键和值。

例如。。。

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.

字典和现实生活中的字典很相似。你有一个词,你有一个定义。你可以查一下这个词并得到它的定义。在这个例子中,你有“水牛”这个词,它的定义是4。它可以与任何其他单词和定义一起工作。先把它们放进字典里。

相关问题 更多 >