[Tutor] Using a string to get at a Variable
hcohen2
hcohen2 at comcast.net
Sun Jan 18 21:29:03 EST 2004
Isr Gish wrote:
>I'm trying to get the data from a variable using a string.
>For example I have three variables named apples, grapes, pears. Then I have a list with these 3 names as strings.
>Now I would like to do a loop on the list and getsthe data from each name.
>
>Any help would be greatly appreciated.
>
>Thanks in Advance
>
>---------------
>Isr Gish
>
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>
Ist,
You are not very explicit on either on what you on working with nor the
sort of object that contains the data you are seeking to extract, hence,
I will just outline an example of my own design.
Let's say you get you set of variables as a tuple: (var_1, var_2, ...,
var_n) - I am going to assume these variables are names of lists. So I
see no real need to convert them to strings. If that is indeed
necessary, skip the entire discussion.
#Intermediate result
names_tuple = (var_1, var_2, ..., var_n)
len_tuple = len(names_tuple)
for j in range(len_tuple):
try:
len_obj = len(var_j)
for i in range(len_obj):
value_of_obj(i) = var_i[i]
try:
print 'Show me the value of %s' %
names_tuple[j],
print var_i[i]
# Or do whatever you have in mind, e.g.
storing in a dictionary, etc.
except ValueError, TypeError, diag: #
regarding the errors I am guessing
print str(diag)
except TypeError, RangeError, diag:
print str(diag)
I am not sure how useful you will find this nor how close it is to
solving the problem you are attacking - just recognize I am new at
python. Moreover, I may miss the clues to the type of problem, since my
specialty is databases and much of the discussion here leaves me a bit
puzzled as to where they are being applied.
In any case, I hope it helps a bit.
Herschel
More information about the Tutor
mailing list