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

tn is a string object. But I want to use this string object as the variable of the same name. So I can expect the result declared as a variable, tn.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
SH Chung
  • 33
  • 3
  • Can you explain better what you mean by "use this string object as the variable of the same name"? And what's the underlying reason for this? – solarc Aug 14 '23 at 05:08
  • 1
    Duplicate of [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – esqew Aug 14 '23 at 05:11
  • don't do this. use a container like a list or a dict – juanpa.arrivillaga Aug 14 '23 at 07:21

1 Answers1

0

It is best to avoid variable variable names; however, if you must, using a dictionary would be much better.

Try something like this:

# create dictionary of variables
variables = {}

variables['tn'] = 'convert'

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

print(variables[variable_name])

See this comment on a similar question as to why variable variable names are problematic.

it's the maintainance and debugging aspects that cause the horror. Imagine trying to find out where variable 'foo' changed when there's no place in your code where you actually change 'foo'. Imagine further that it's someone else's code that you have to maintain...

Hope this helps

futium
  • 90
  • 1
  • 9