strings question

Andrei project5 at redrival.net
Fri Mar 12 13:47:11 EST 2004


Faheem Mitha wrote on Fri, 12 Mar 2004 18:03:05 GMT:

> If I am given two strings, named foo and bar, what is the most elegant
> way to create a string object whose name is the value of foo and whose
> value is the value of bar? I have done some searching + looking in my
> introductory textbook "Learning Python" but have not come up with an
> answer yet.

You could use exec (potentially dangerous if not all code being exec-ed is
under your control):

>>> f = 'foo'
>>> b = 'bar'
>>> exec '%s = b' % f
>>> foo
'bar'

You could also manipulate the globals or locals dictionary:

>>> globals()[f] = b*2
>>> foo
'barbar'
>>> locals()[f] = b*3
>>> foo
'barbarbar'

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.



More information about the Python-list mailing list