A variables variables

G

Gandalf

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

thanks!
 
C

castironpi

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

thanks!

Here's one idea.

Also, you can look up locals() and globals(), or getattr, if you do
this in a class.
 
M

Mohamed Yousef

i don't know if this volatiles array condition or not
but any way

q='asd'
asdasd=20
print globals()[q+'asd']
 
B

Benjamin

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

Doing this sort of thing in Python is very anti idiom.
how can i do it with no Arrays using  python

Why would you not want to use a list? I see no reason not to.
 
T

Terry Reedy

Gandalf said:
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. 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']
 
M

Maric Michaud

Le Sunday 24 August 2008 03:24:29 Terry Reedy, vous avez écrit :
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()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top