954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Force String to use Global Variable

Hi, please help me. Say I have 2 lines of code below. I want to "print ranking" and have result of "1" (force string to use global variable) instead of the letter "a". What are the methods available?

a=1
ranking = "a"


Can you please help me out? I'm noob at python. Thanks.

ron126
Newbie Poster
7 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 
>>> a = 1
>>> ranking = "a"
>>> print 'ranking is %s' % globals()[ranking]
ranking is 1

This is more of a ugly hack and dont do it like this.
You are better of bulding a dictionary.
Something like this

>>> d = {'ranking_a': 1, 'ranking_b': 2}
>>> d['ranking_a']
1

If problems post a better description of what you are trying to do.

snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
 

Thanks for your reply, but to be more specific, this is what I want to do:

a=1
b=2
ranking = ["a","b"]
x = ranking[0] + ranking[1] #which is a+b in the ranking list

But now, the problem is that the "a" and "b" in the ranking list is in string and so I can't show the result for my x, even though my global variable does state int value for a and b. *the result should be 3*

Do you know any methods to solve this? Like forcing string to use global variable?

ron126
Newbie Poster
7 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 
>> my_globals = dict(a=1, b=2)
>>> ranking = ['a', 'b']
>>> x = eval("%s + %s" %(ranking[0], ranking[1]), my_globals)
>>> x
3
>>>


I bet you are not using the correct approach in your code, what you are trying to do to do this kind of indirection?

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 
>>> a = 1
>>> b = 2
>>> ranking = ['a', 'b']
>>> sum(globals()[i] for i in ranking)
3

Like this,but not nice.
You see PyTony make a dictionary and than take out values.

But you have to rethink this.
string 'a' and 'b' in ranking is just string not pointing to anything.
You can bind string 'a' 'b' to variable a b.

>>> d = {}
>>> d[ranking[0]] = a
>>> d[ranking[1]] = b
>>> d
{'a': 1, 'b': 2}

Or just make a dictionary in first place,not confusing stuff like now.

snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
 

Thanks snippsat, for the binding technique :D

ron126
Newbie Poster
7 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You