[Tutor] Addressing a variable whose name is the value of a string
John Clark
clajo04 at mac.com
Sun Apr 8 19:51:38 CEST 2007
Bob Gailer wrote:
>Andreas Pfrengle wrote:
>> Hello,
>>
>> I want to change the value of a variable whose name I don't know, but
>> this name is stored as a string in another variable, like:
>>
>> x = 1
>> var = 'x'
>>
>> Now I want to change the value of x, but address it via var.
>
>exec is the statement for doing this, but the need to do this can always be
met better by using a dictionary instead of global variables.
>
I think you can also do this with
globals()[var]
-or-
locals()[var]
But I am not sure what the pros/cons for doing something like this would
be...
-jdc
More information about the Tutor
mailing list