2016-03-09 63 views
0

我有一个可能很容易的问题,我似乎无法弄清楚如何。如何做这样的事情:如何打印字符串的值,而不是自己的字符串

race = goblin #I change the race here 


goblingrowth = 200 
humangrowth = 300 
orgegrowth = 400 

print (race + "growth") #In this case, it will print the string "goblingrowth" in 
python, but I want it to print the value of the variable (goblingrowth), 
which is 200, and i have to do it this way. 

任何帮助,将不胜感激,谢谢你能做到这一点

+0

考虑使用字典。 –

回答

3

你可以只存储值在字典中,而不是作为独立变量。

growths = {'goblin': 200, 'humans': 300, 'ogre': 400} 
print growths[race] 
+0

非常感谢所有的答案,我刚开始python并且是weeb级别的,那些技巧会派上用场! – pythonsohard

-1

一种方法是访问locals()字典持有你的代码的局部变量和获得的价值你所拥有的字符串中的变量。例如:

race = 'goblin' #I change the race here 

goblingrowth = 200 
humangrowth = 300 
orgegrowth = 400 

print(locals()[race + 'growth']) # this accesses the variable goblingrowth in the locals dictionary 

会输出200。希望这可以帮助!

+1

我认为有人低估了你,因为使用'eval'确实不是一个好主意。我会建议重新工作你的解决方案。 – idjaw

+0

'eval'有什么问题? – MarkyPython

+1

阅读[this](http://stackoverflow.com/a/1832957/1832539)和[this](http://stackoverflow.com/a/9384005/1832539)让你开始。这不是最佳做法,使用起来相当危险。 – idjaw

0

只需将goblingrowth添加到您的打印中,如下所示。然而,你要这样做的方式,你必须将你的变量转换为一个字符串(因为你的goblingrowth是一个int),这不是很理想。你可以这样做:

print(race + " growth " + str(goblingrowth)) 

然而,这将是更合适的,强烈推荐来构建你的输出是这样,而不是使用字符串格式化:

print("{0} growth: {1}".format(race, goblingrowth)) 

上面发生了什么事,是你设置因此{0}表示您提供的第一个参数用于格式化并设置在字符串的该位置,即race,则{1}将指示提供给格式的第二个参数,即goblingrowth。你其实不需要需要提供这些数字,但我建议你阅读下面提供的文档,以获得更多的了解。

阅读关于字符串格式化here。这将有很大的帮助。

2

一个更好的方法来做到这一点是有一个类来表示你的不同类型的生物体。然后您可以为每场比赛创建一个实例,设置属性。您将可以方便地访问特定生活的所有属性。例如:

class Living(object): 
    def __init__(self, name, growth): 
     self.name = name 
     self.growth = growth 

goblin = Living("goblin", 200) 
human = Living("human", 300) 
ogre = Living("ogre", 400) 

for living in (goblin, human, ogre): 
    print(living.name + " growth is " + str(living.growth)) 

此输出:

goblin growth is 200 
human growth is 300 
ogre growth is 400