Making variable from a variable
Dave Benjamin
ramen at lackingtalent.com
Thu Oct 9 03:18:16 EDT 2003
In article <dcf37d82.0310082219.da7d175 at posting.google.com>, Polerio Babao Jr.II wrote:
> in php
>
><?
>
> $a = 'b';
> ${$a} = 'c';
> print "$a $b";
>
> ?>
>
> output is
>
> b c
Your PHP example can be accomplished with a dictionary, which is a better
way to go altogether in my opinion:
>>> d = {}
>>> d['a'] = 'b'
>>> d[d['a']] = 'c'
>>> print '%(a)s %(b)s' % d
b c
But if you absolutely must muck with the locals:
a = 'b'
locals()[a] = 'c'
print '%(a)s %(b)s' % locals()
Don't blame me if it's not backward/forward compatible, has unexpected
side-effects, or otherwise blows up in your face. I'm just the messenger.
Python 2.1, 2.2, and 2.3 tested.
<soapbox>
And don't program that way, anyway. It's just SILLY. (Believe me. I used to
write plenty of PHP.)
</soapbox>
Peace,
Dave
--
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
More information about the Python-list
mailing list