使用字符串对象作为同名变量 [duplicate]

Use a string object as the variable of the same name [duplicate]

提问人:SH Chung 提问时间:8/14/2023 最后编辑:John KugelmanSH Chung 更新时间:8/14/2023 访问量:48

问:

tn = 'convert'
print('t'+'n')

tn是一个字符串对象。但是我想将这个字符串对象用作同名变量。因此,我可以期望将结果声明为变量 .tn

Python 字符串 变量

评论

0赞 solarc 8/14/2023
你能更好地解释一下“使用这个字符串对象作为同名变量”是什么意思吗?造成这种情况的根本原因是什么?
1赞 esqew 8/14/2023
如何创建变量变量?
0赞 juanpa.arrivillaga 8/14/2023
别这样。使用列表或字典等容器

答:

0赞 futium 8/14/2023 #1

最好避免变量变量名称;但是,如果必须的话,使用字典会好得多。

尝试这样的事情:

# create dictionary of variables
variables = {}

variables['tn'] = 'convert'

# create variable name
variable_name = 't' + 'n'

print(variables[variable_name])

请参阅此评论,了解为什么变量变量名称有问题。

正是维护和调试方面导致了恐怖。想象一下,当你的代码中没有实际更改“foo”的地方时,试图找出变量“foo”在哪里发生了变化。进一步想象一下,你必须维护的是别人的代码......

希望这会有所帮助