1

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

SAAD
  • 759
  • 1
  • 9
  • 23
  • Umm I kind of hope there isn't any :p That's messy! Do you absolutely, positively need that? – Roberto Dec 11 '13 at 00:19
  • 2
    keep your data out of your variable names. Use a `dict` or *maybe* `getattr`, depending on the situation. – roippi Dec 11 '13 at 00:20
  • 1
    See if this thread helps: http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python it contains comments about `getattr`, `exec`, `eval` and why it's actually best to use dictionaries :) – Roberto Dec 11 '13 at 00:26

2 Answers2

1

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.

Thomas
  • 6,515
  • 1
  • 31
  • 47
0

You can use exec("").

But you really(!!!) don't want to.

>>> name="myVarName"
>>> exec(name+"='VarData'")
>>> myVarName
'VarData'
MattDMo
  • 100,794
  • 21
  • 241
  • 231
Yaron
  • 233
  • 1
  • 14