String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.
Rules for naming a variableA variable name can only have letters (both uppercase and lowercase letters), digits and underscore. The first letter of a variable should be either a letter or an underscore. There is no rule on how long a variable name (identifier) can be.
Use the for Loop to Create a Dynamic Variable Name in Python Along with the for loop, the globals() function will also be used in this method. The globals() method in Python provides the output as a dictionary of the current global symbol table.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With