How to get a variables value within a variable

This is the place for queries that don't fit in any of the other categories.

How to get a variables value within a variable

Postby pnelsonsr » Thu Dec 12, 2013 1:10 am

If I have a variable
Code: Select all
myvar1='hello'

and a variable that hold the variables name
Code: Select all
showvar='myvar1'

how can I
Code: Select all
print showvar

so it displays the value of myvar1 (ie 'hello'?)
Last edited by pnelsonsr on Tue May 06, 2014 3:44 pm, edited 3 times in total.
pnelsonsr
 
Posts: 25
Joined: Thu Dec 12, 2013 12:48 am

Re: How to get a variables value within a variable

Postby micseydel » Thu Dec 12, 2013 1:39 am

I presume you meant for "thevar" and "myvar1" to be the same. You can do the following, although there is probably a better way to achieve it and if you show us what you're trying to achieve we can happily show you the preferred way
Code: Select all
>>> proxy_var = "hello"
>>> desired_var = "proxy_var"
>>> print locals()[desired_var]
hello
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 1179
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: How to get a variables value within a variable

Postby pnelsonsr » Thu Dec 12, 2013 1:51 am

micseydel wrote:I presume you meant for "thevar" and "myvar1" to be the same. You can do the following, although there is probably a better way to achieve it and if you show us what you're trying to achieve we can happily show you the preferred way
Code: Select all
>>> proxy_var = "hello"
>>> desired_var = "proxy_var"
>>> print locals()[desired_var]
hello


yes thevar (and I fixed it above)

So locals()[thevar]...

I was just working with var() as in

print var()[thevar] and found that this worked as well. Thanks for the response.
pnelsonsr
 
Posts: 25
Joined: Thu Dec 12, 2013 12:48 am

Re: How to get a variables value within a variable

Postby micseydel » Thu Dec 12, 2013 2:17 am

I had meant to lock your post (oops) but it doesn't look like you changed it. And I believe you mean vars() which works too, but again, you probably shouldn't be doing that so if you let us know what you were trying to accomplish we can advise you about the proper way to do that thing.
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 1179
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 5 guests