8
votes

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.

3
What's wrong with a + b? - jonrsharpe
what I want to have "a + b" as a variable name, so i could in theory go "a + b" = 5, and then have a variable with the name "a + b" with value 5 - kyrenia
Use a dict and put a+b as key - Tim
That seems like a terrible idea, for exactly the reasons your research has already given you. - jonrsharpe

3 Answers

15
votes
>>> 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 ;)

2
votes

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

1
votes

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

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

data[a+b] = 42