2016-03-09 61 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 
相關問題