Python 如何将字符串本身作为变量
我试了各种方法,但都没有找到解决办法 我被困在一个应用程序中,我将给出类似的例子 我有一些弦Python 如何将字符串本身作为变量,python,python-2.7,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"
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'的名称。
有什么方法可以做到这一点吗?您可以使用
>>> 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:doing
arg==arg
是完全多余的,它将始终计算为True我假设您的目标是间接访问值。在这种情况下,考虑将变量放在类或字典中。下面是课堂教学法的一个例子:
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
if(arg==arg)
尽管有多余的括号,但始终为真:任何对象始终等于自身。这本质上使你无法估量你到底在问什么!是的,那是因为疏忽将arg等同于arg,谢谢:)