10

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.

4
  • What's wrong with a + b? Commented Mar 31, 2015 at 16:30
  • 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 Commented Mar 31, 2015 at 16:31
  • 1
    Use a dict and put a+b as key Commented Mar 31, 2015 at 16:32
  • 2
    That seems like a terrible idea, for exactly the reasons your research has already given you. Commented Mar 31, 2015 at 16:32

3 Answers 3

22
>>> 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 ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect - thanks, while I do not disagree that this is probably a bad idea (and do not believe that I am "the one exception to the rule"), I am grateful for now knowing how to do it :-)
Oh I just meant a +1, I know you have to wait to accept it :-)
4

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

Comments

1

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

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

data[a+b] = 42

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.