a=1
b=2

x="ab"

How do I "print x[0]" and get a result of "1" (int), instead of letter "a"? (make the string use global variable)

Please help me, thanks.

def gv(s):
    return globals()[s]

print gv(x[0])

OMGGGGGGGGG, Thanks you Gribouillis

Oh wait, there's another problem, what if the letter in the string doesn't have global variable? That function will cause error. Is there a way to ignore global variable if letter in the string doesn't have global variable, for example making the class function optional if the letter doesn't have global variable?

This came up recently and I wan to say that there is 99% chance that you are doing something stupid. Usually one would use dictionary, like

import string 
d  = dict((a,c) for c,a in enumerate(string.lower, 1))

Anyone else have other answer?

Say my code is something like:

print gv(x[0])

a=1
b=2

x = "abcde12345...." #The string is randomly generated

def gv(s):
return globals()[s]

Basically I want to use gv functions to print the letters in string "x" out. If any letter in "x" has global variable, it will use global variable, else it will just the letter unchanged.

If any letter in "x" has global variable, it will use global variable, else it will just the letter unchanged.

Here it is

def gv(s):
    return globals().get(s, s)

Here we go again:ooh:

>>> a = 1
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'a': 1, '__package__': None}

What`s happen here is that we take a look into the global namespace.
We see that global namespace store 'a': 1 as a dictionary.
Let create a visible dictionary.

>>> d = {'a': 1}

Now we shall use both.

>>> globals()['a']
1
>>> d['a']
1
>>>

So a advice dont use python internal working like global namespace as a dictionary.
The code get much clearer if you make a ordinary dictionary.

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.