I have a number of variables that I want to modify (a bunch of strings that I need to convert into ints). Is there an easy way to do that other than saying:
> a = int(a) > b = int(b) > c = int(c)
It may not matter to you, at the moment, but a = int(a) is not strictly 'modifying a variable'. Instead int(a) creates a new int object, if possible, from the object that a is currently bound to. Then a is rebound to the new object.
I tried
> [i = int(i) for i in [a, b, c]]
You can't make an assignment in a list comprehension. If your 'variables' are object attributes, you could do: [setattr(obj,name,int(getattr(obj,name)) for name in [list of attribute names]]
but that didn't work because it was creating a list with the values of a, b and c instead of the actual variables themselves, then trying to set a string equal to an integer, which it really didn't like.
Marc
For your problem as stated:
>>> a=b=c="1" >>> for var in ["a","b","c"]: ... exec "%s = int(%s)" % (var,var) ... >>> a,b,c (1, 1, 1) >>>
But don't do this, except as a "one-off" data crunching exercise
Michael
-- http://mail.python.org/mailman/listinfo/python-list