[Tutor] from string to variable name
wesley chun
wescpy at gmail.com
Fri Oct 6 01:30:20 CEST 2006
On 10/5/06, frank h. <frank.hoffsummer at gmail.com> wrote:
> hello, i have a string variable that contains a name that I want to use as
> a variablename
setattr() won't work because that's only for objects which have
attributes. you're talking about creating a (global or local)
variable. i will also recommend you use a dictionary too... it's
flexible and powerful.
but if you *have* to do it, to paraphrase jonathon's example:
>>> myString = 'rotationalSpeed'
>>> exec '%s = 4500' % myString
>>> print rotationalSpeed
4500
it's ugly but works. this example is more useful if you're planning on
dynamically-generated lots of Python code to execute, not just a
single assignment like this.
good luck!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com
wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
More information about the Tutor
mailing list