3

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 ]

2 Answers 2

15

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}
Sign up to request clarification or add additional context in comments.

3 Comments

If using Python 2.6 or earlier: d = dict((name, re.compile("%s=[a-z]+&" % name) for name in a)
then what if I later on want to use the above assigned regex on a string?
@abhinav: Simply retrieve it from the dictionary: d["nt"] etc.
0

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.

2 Comments

Changing the dictionary returned by vars() or locals() is not allowed. You can only change the dictionary returned by globals(). Your code only works because you executed it at global scope, it would not work inside a function.
True. This obviously isn't a tenable solution, just an interesting quirk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.