So i have code like this
varName = 'test'
varContents = 'something'
My question is:
How do i create a variable with the name of the contents of varName
, having contents containing the contents of varContents
?
So i have code like this
varName = 'test'
varContents = 'something'
My question is:
How do i create a variable with the name of the contents of varName
, having contents containing the contents of varContents
?
Generally you'll want to avoid doing this - especially if you are dealing with user inputs, but you can use the exec()
function. It runs a string passed into it as code, so you can do something like:
varName = 'test'
varContents = 'something'
exec(f"{varName} = '{varContents}'")
print(test)
A better way of storing data with a dynamic key is with a dict like this:
myDict = {}
varName = 'test'
varContents = 'something'
myDict[varName] = varContents
print(myDict[varName])
you can create variables like this :
locals()['newVar'] = "local variable"
print (newVar)
globals()['newGlobalVar'] = "global variable"
print (newGlobalVar)
so you could do this :
locals()[varName] = varContents
# Or
globals()[varName] = varContents