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.

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?

Edited 4 Years Ago by ron126: n/a

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

Edited 4 Years Ago by pyTony: n/a

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.

Edited 4 Years Ago by ron126: n/a

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.

Edited 4 Years Ago by snippsat: n/a

This article has been dead for over six months. Start a new discussion instead.