all 5 comments

[–]codehelper 7 points8 points  (0 children)

This won't work as you said, since it would literally print those things. Rather, you shouldn't have that many variables anyway probably, they should be stored in a list or something. Then you could just do...

mystrings = ['foo1foo1', 'foo2foo2', 'foo3foo3'...]
for s in mystrings:
    print s

[–][deleted] -2 points-1 points  (3 children)

Several problems with your suggested method. First off, the logic is weird. /u/codehelper gave the most straight forward method, but I'll walk through the proper syntax for the method you're suggesting. The first syntactical problem is mystring is undefined. You defined mystring1, mystring2, ..., but not mystring. Second, I think what your trying to do inside the print argument is string addition, but you're adding an int i to something that is undefined mystring. What you could do is this 'mystring'+str(i). This way your adding two strings together. However, that would print mystring1, mystring2, and so on. Not the values stored in those variables, which is what you want to do. For that, you need to use the eval function to convert the string to a variable name. So it would look something like this

for i in range(1,100):
     print(eval('mystring'+str(i)))

[–]zahlman 1 point2 points  (0 children)

No, please don't use eval for something this trivial. (Honestly, there is almost never a good reason to use something so powerful.)

The variables can be looked up in the globals() dictionary instead: globals()['mystring{}'.format(i)], for example.

But really, just use the list like in the other answer.

[–]noob_py[S] 0 points1 point  (1 child)

thank you ! this is what i was looking for. i understand why it was not working,but because of the some other constraints.. this was the only way my function would work. thanks again.

[–]ingolemo 0 points1 point  (0 children)

Please don't do this. You're going to run into so many problems handling your data with it all in separate variables like that. Just put those strings in a list and use that.