Get variable name as string python

Code examples

4
0

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'
0
0

python get variable from string

some_variable = "here is a string stored in this variable"
# Get the variable name from a string by the eval() function:
# Notice how the parameter is a string but the print() function still returns the variable
print(eval("some_variable"))

# More advanced usage
import random
thing1 = "thing 1"
thing2 = "thing 2"
thing3 = "thing 3"

number = random.randint(1, 3)
variable_as_a_string = "thing" + str(number)

print(eval(variable_as_a_string))

In other languages

This page is in other languages

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................
Балгарскі
..................................................................................................................
Íslensk
..................................................................................................................