Reputation: 177
I have a list of items in python something like this: input:
a=['nt','mt','pt']
I want to make each item in the above list as a variable and then assign that variable to a regex involving that variable.
output: I want something like this:
nt=re.compile("%s=[a-z]+&" %nt)
mt=re.compile("%s=[a-z]+&" %mt)
pt=re.compile("%s=[a-z]+&" %pt)
how do i go about doing this ??? Thanks. [sorry didn't pose the question in the best way possible ]
Upvotes: 3
Views: 6656
Reputation: 817
Unquestionably best to use dictionary keys, not variables. But FYI in Python variables are actually stored in a dictionary anyway, which you can access by calling vars()
or locals()
. That means it is possible to create variables dynamically just by assigning to this dictionary, e.g.:
>>> new_var_name = 'my_var'
>>> vars()[new_var_name] = "I'm your new variable!"
>>> print my_var
"I'm your new variable!"
To be honest I don't know how tampering with vars()
could ever be justifiable. But it's interesting, at least. Anyway, use Sven Marnach's answer.
Upvotes: 0
Reputation: 601679
Keep data out of your variable names. Don't use variables, use a dictionary:
d = {name: re.compile("%s=[a-z]+&" % name) for name in a}
Upvotes: 15