A variables variables
Maric Michaud
maric at aristote.info
Sun Aug 24 10:02:30 EDT 2008
Le Sunday 24 August 2008 03:24:29 Terry Reedy, vous avez écrit :
> Gandalf wrote:
> > how can I declare a variable with another variable name?
> >
> > for example I will use PHP:
> >
> > $a= "hello";
> >
> > $a_hello="baybay";
> >
> > print ${'a_'.$a) //output: baybay
> >
> >
> > how can i do it with no Arrays using python
>
> Others have given you the direct answer.
Well using locals() is the right answer, it is a very bad use case for eval.
> But using lists or dicts is
> almost always a better solution in Python than synthesizing global/local
> namespace names.
>
> a={'hello':'baybay'}
> print a['hello']
But locals() *is* an already made dict, very convenient for use locally and
read-only.
>>>[155]: var1 = "easy"
>>>[156]: var2 = "proper"
>>>[157]: var3 = "locals"
>>>[158]: print "a %(var2)s and %(var1)s use of %(var3)s with %(var3)s()" %
locals()
a proper and easy use of locals with locals()
--
_____________
Maric Michaud
More information about the Python-list
mailing list