Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

Possible Duplicate:
How do I do variable variables in Python?

I have a variable with a string assigned to it and I want to define a new variable based on that string.

foo = "bar"
foo = "something else"   

# What I actually want is:

bar = "something else"
share|improve this question

marked as duplicate by jogojapan, JBernardo, Karl Knechtel, monkut, Jeremy Banks Jul 19 '12 at 19:09

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

9  
You probably DON'T want that. Why are you trying to do it? – JBernardo Jul 19 '12 at 4:03
2  
No you don't. The reason you have to use exec is because locals() doesn't support modifications. locals() doesn't support modifications because it would make the implementation more complex and slower and is never a good idea – John La Rooy Jul 19 '12 at 4:04
1  
Similar Post: stackoverflow.com/questions/1373164/… – Kartik Jul 19 '12 at 4:08

You will be much happier using a dictionary instead:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"
share|improve this answer
4  
It does not seem to address the question. – dnsmkl Nov 5 '15 at 19:52

You can use exec for that:

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>> 
share|improve this answer
26  
+1 because he answered the question (as bad an idea as it may be). – mgalgs Jun 25 '13 at 3:39

You can use setattr

name= 'varname'
value= 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print self.varname
#will print 'something'

But, since you should inform an object to receive the new variable, I think this only works inside classes.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.