-2

I have a string, which is a variable name. I have to pass that variable to another function to get proper output. I tried using backtick and other techniques. What are the other ways to do that? I am a beginner and don't have much expertise in python.

for i in range(1,65):
period_writer.writerow([i, max('test' + `i`)])

I want to pass the variable as test1, test2, ..... test64 to max() function and get the maximum value of those variables.

Thanks in advance

1 Answers1

1

You are trying to do this:

test1 = something
test2 = something else

for i in range(1,2):
    print('test' + str(i))

however, that won't work because strings cannot be used as variable names. You can cheat somewhat by using locals(), which creates a dictionary of local variables:

test1 = something
test2 = something else

for i in range(1,2):
    print(locals()['test' + str(i)])

but what you really should be doing is putting your variables into a dictionary (or list!) in the first place.

d = {'test1': something,
     'test2': something else}

for i in range(1,2):
    print(d['test' + str(i)])

# or even better
tests = [something, something else]
for test in tests:
    print(test)

# even better, what you're trying to do is this:
for i, test in enumerate(tests):
    period_writer.writerow([i+1, max(test)])

This makes it much clearer that the variables belong together and will run faster to boot.

Turksarama
  • 1,136
  • 6
  • 13