Answers for "use variable name as string python"

4

how to use a string variable as a variable name in python

#works only inside classes
name  = 'varname'
value = 'something'

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

print (self.varname)
#will print 'something'
Posted by: Guest on October-10-2020
0

python use variable name as variable

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
Posted by: Guest on April-28-2021

Code answers related to "use variable name as string python"

Python Answers by Framework

Browse Popular Code Answers by Language