I have variables text1
, text2
, text3
. I want to print them.
for i in range(1, 4):
text = 'text' + str(i)
print(text)
This code prints strings text1 text2 text3 , not the content of them.
I have variables text1
, text2
, text3
. I want to print them.
for i in range(1, 4):
text = 'text' + str(i)
print(text)
This code prints strings text1 text2 text3 , not the content of them.
The correct way to do this is python is to use dictionaries. At the moment you are taking a string object, referenced by the variable text which contains the string 'text' and concatenating it with string object 'i' to make a new string object 'texti' and making the text variable reference that. Ie all you do is make a new string object and reference it with the same variable.
What you want to do is make a dictionary where the keys are the variables and the values contain your referenced objects.
variables = {'var1':'Hello', 'var2':'World'}
now if you want to get 'Hello' you would
print(variables['var1'])
If for some reason you need to do this, you can use the function eval
to parse a string as a python expression. Just replace your print(text)
line with
print(eval(text))
But as James Lingham said, this is not a good idea. It's confusing to read and prone to error, and much simpler solutions exist. For example, you could just create a list [text1, text2, text3]
, and then loop through them.
text = [text1, text2, text3]
for i in text:
print(i)
While I concur with the other comments, there is a way. But please try to find a better way to do this.
for i in range(1,4):
text = 'text' + str(i)
print(eval(text))