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.

>>> 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.

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?

>> 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?

>>> 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.

Thanks snippsat, for the binding technique :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.