Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create variable name from two string in python

I am looking to create a variable name from two strings in Python, e.g.:

 a = "column_number"
 b = "_url1"

and then be able to get a variable name "column_number_url1" that I can use.

I appreciate this is in general not a good idea - there are numerous posts which go into why it is a bad idea (e.g. How do I create a variable number of variables? , Creating multiple variables ) - I mainly want to be able to do it because these are all variables which get defined elsewhere in the code, and want a easy way of being able to re-access them (i.e. rather than to create thousands of unique variables, which I agree a dictionary etc. would be better for).

As far as I can tell, the answers in the other posts I have found are all alternative ways of doing this, rather than how to create a variable name from two strings.

like image 370
kyrenia Avatar asked Mar 31 '15 16:03

kyrenia


3 Answers

>>> a = "column_number"
>>> b = "_url1"
>>> x = 1234
>>> globals()[a + b] = x
>>> column_number_url1
1234

The reason that there aren't many posts explaining how to do this is because (as you might have gathered) it's not a good idea. I guarantee that your use case is no exception.

In case you didn't notice, globals() is essentially a dictionary of global variables. Which implies that you should be using a dictionary for this all along ;)

like image 171
Joel Cornett Avatar answered Oct 06 '22 11:10

Joel Cornett


You can use a dictionary:

a = "column_number"
b = "_url1"
obj = {}
obj[a+b] = None
print obj #{"column_number_url1": None}

Alternatively, you could use eval, but remember to always watch yourself around usage of eval/exec:

a = "column_number"
b = "_url1"
exec(a+b+" = 0")
print column_number_url1 #0

eval is evil

like image 31
A.J. Uppal Avatar answered Oct 06 '22 10:10

A.J. Uppal


As an alternative to Joel's answer, a dictionary would be much nicer:

a = "column_number"
b = "_url1"
data = {}

data[a+b] = 42
like image 22
Finwood Avatar answered Oct 06 '22 10:10

Finwood