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 a Letter in String to use Global Variable

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.

ron126
Newbie Poster
7 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 
def gv(s):
    return globals()[s]

print gv(x[0])
Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

OMGGGGGGGGG, Thanks you Gribouillis

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

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?

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

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))
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

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.

ron126
Newbie Poster
7 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 
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)
Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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.

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

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You