如何将字符串本身作为变量

时间:2015-02-10 06:08:58

标签: python python-2.7

我试过各方面,无法得到任何解决方案。

我被困在一个应用程序中,我会给出类似的例子,

我有一些字符串,

arg = "school"
arg_2 = "college"

school = "enjoy"
college = "study"

我想在下面的代码中使用它

if ( arg == arg  )
  \\ want to print content of school here, 
else
  \\ want to print content of college here,

我可以在字符串' arg'的帮助下制作吗?只要?我不想使用字符串' school'这里。 有没有办法做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用locals执行此操作

>>> arg = "school"
>>> arg_2 = "college"
>>> school = "enjoy"
>>> college = "study"
>>> locals()[arg]
'enjoy'
>>> locals()[arg_2]
'study'

所以你可以简单地打印一个像

这样的语句
>>> "{} at {}".format(locals()[arg], arg)
'enjoy at school'
>>> "{} at {}".format(locals()[arg_2], arg_2)
'study at college'

PS:执行arg == arg完全是多余的,它总是会评估为True

答案 1 :(得分:0)

我假设你的目标是间接访问价值观。在这种情况下,请考虑将变量放在类或字典中。以下是类方法的示例:

class mydata(object):
    arg = "school"
    arg_2 = "college"

    school = "enjoy"
    college = "study"

    def value_of_value(self, s):
        return getattr(self, getattr(self, s))

x = mydata()
print 'arg->', x.value_of_value('arg')
print 'arg_2->', x.value_of_value('arg_2')

这会产生:

arg-> enjoy
arg_2-> study