How can I generate a variable name from a string (say a concatenation of a letter and a number) ?
In Matlab, this task can be easily done using genvarname
How can I generate a variable name from a string (say a concatenation of a letter and a number) ?
In Matlab, this task can be easily done using genvarname
Here's a really bad way (undefined behavior), but I think it shows the path to a more reasonable technique.
Your current namespace is really a dictionary under the covers:
>>> local_namespace = locals()
>>> name = "myVarName"
>>> local_namespace[name] = 'VarData'
>>> myVarName
'VarData'
But that's not very DRY - you have to write the name of the variable twice! It would be nice to use a variable that stored the name of our dynamically created variable so we didn't have to type it twice:
>>> name
'myVarName'
obviously doesn't work for this. But we can use our dictionary again:
>>> local_namespace[name]
'VarData'
So now we can store and recall the value associated with our variable. But wait - there's no need to use the special locals()
dictionary for this - an ordinary dictionary will do!
>>> d = {}
>>> d[name] = 'VarData'
>>> d[name]
'VarData'
And now we have all these added benefits, like being able to keep track of the names of several of these variables in a list:
>>> l = []
>>> l.append('myVarName')
>>> l.append('anotherVarName')
Dictionaries even do this for us:
>>> d['anotherVarName'] = 123
>>> d.keys()
['myVarName', 'anotherVarName']
Unless you're doing terrifically wacky things, it's hard to imagine how constructing variable names could be more useful than using a dictionary.
You can use exec("")
.
But you really(!!!) don't want to.
>>> name="myVarName"
>>> exec(name+"='VarData'")
>>> myVarName
'VarData'