简体   繁体   中英

Create variable name from two string in python

I am looking to create a variable name from two strings in Python, eg:

 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 (eg 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 (ie 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.

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

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

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

data[a+b] = 42

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM