Is there any other method in Python that can change a string to a variable?
For example, I have some variables named button1, button2, button3, etc. I want to operate on them in a loop. If I don’t want to use eval, anything else suitable?
Is there any other method in Python that can change a string to a
Share
There’s
globalsandlocalswhich return a dictionary mapping of your current namespace.e.g.:
globalsshould be used if the variable is defined at the module level,localsshould be used for everything else. In your case, I would think thatlocals()['button1']would do the trick.Having said that, it’s probably a better idea to just put the buttons in a dictionary in the first place.