changing a strig to a variable

Gerhard Häring gh_pythonlist at gmx.de
Tue Oct 9 13:25:38 EDT 2001


On Tue, Oct 09, 2001 at 11:44:11AM -0400, Raibatak Das wrote:
> hi, 
> 
> this might be a silly question but i would greatly appreciate an answer.
> is there any way to convert a string to a variable name. that is, suppose
> i have x = 'var' and i want to do, say, var=13 is there an easy way to do
> so?

Most of the time, this isn't a good idea and can be replaced by
alternative constructs, like dictionaries. For example:

salaries = {}           # creates a dictionary
name = "Joe"            # key for the dictionary
salaries[name] = 5000   # store a value in the dictionary

A dictionary is a mapping from keys to values. In the above example, I
mapped employee names to their salaries. The keys can be of any
immutable type (strings, ints, but *not* lists, for example). The values
can be of any type.

If you really really need to do what you asked for (unlikely, I never
did), you can use the exec statement or the eval() builtin function.

x = 'var'
statement = "%s = 'Joe'" % x
exec statement

or maybe better: exec statement in globals(), locals()

Perhaps you want to replace globals() and locals() with custom
dictionaries your exec statement works on instead of directly working on
the "real" global and local namespace.

The eval function works similarly, but returns the value of the
expression instead of executing a statement.

But exec and eval should only be used as a last resort. Did you have
something special in mind? If you tell us what we could most probably
describe a better way of accomplishing this task.

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




More information about the Python-list mailing list