如何打印字符串的值,而不是它所在的字符串

2024-09-30 22:10:52 发布

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

我有一个可能很简单的问题,我似乎不知道该怎么做。如何做到这一点:

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. 

任何帮助都将不胜感激,谢谢


Tags: thetoinhereitthischangecase
3条回答

更好的方法是用一个类来表示不同类型的生命实体。然后可以为每个竞赛创建一个实例,设置属性。这样你就可以方便地使用给定生活的所有财产。例如:

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

只需将goblingrowth添加到打印中,我将在下面显示。但是,按照您的方法,您必须将变量转换为字符串(因为您的goblingrowth是int),这不是很理想。您可以这样做:

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

但是,更恰当的做法是,强烈建议您这样构造输出,而不是使用字符串格式:

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

上面的情况是,您正在将参数设置到字符串中的每个位置,因此{0}表示您提供的第一个参数用于格式化并设置在字符串的该位置,即race,然后{1}将表示提供给格式化的第二个参数,即goblingrowth。实际上,您不需要提供这些数字,但我建议您阅读下面提供的文档以了解更多信息

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

您可以将这些值存储在字典中,而不是作为单独的变量

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

相关问题 更多 >