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"
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"
You can use exec
for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
You will be much happier using a dictionary instead:
my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"
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, this only works inside classes or modules.