Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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

python use variable name as variable

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>> 
Comment

python use variable name as string

>>> foo = dict()
>>> f'{foo=}'.split('=')[0]
'foo'
Comment

PREVIOUS NEXT
Code Example
Python :: join function python 
Python :: float python 
Python ::  
Python :: np.random.choice 
Python :: how to address null in python 
Python ::  
Python :: python secret 
Python :: numpy index of first true value 
Python :: django model choice field from another model 
Python :: scrape website with login python selenium 
Python :: pandas remove multi header from dataframe 
Python :: reading files in python 
Python :: python last index of item in list 
Python ::  
Python :: swapping variables 
Python :: NumPy roll Syntax 
:: FileSystemStorage django 
Python :: python classes and objects 
Python :: django venv activate 
Python :: python tutorial 
Python :: save variable to use in other jupyter notebook 
Python :: pandas find fifth caracter in field and change cell based on that number 
Python :: checking length of sets in python 
Python :: convert 2 lists into dictionary 
Python :: python math ln 
Python :: qr code scanner using opencv 
Python :: python string contains substring ignore case 
Python :: python find closest date 
Python :: change value in tuple 
Python :: double underscore methods python 
ADD CONTENT
Topic
Content
Source link
Name
1+8 =