1

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.

  • 3
    Don't try to dynamically create variables. That's the wrong way. Use a [dictionary](https://docs.python.org/3/library/stdtypes.html#dict) instead. – Christian Dean Jun 02 '17 at 02:08

4 Answers4

3

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'])
syntaxError
  • 896
  • 8
  • 15
1

You don't want to do this, try using a list or a dictionary instead.

James Lingham
  • 419
  • 1
  • 3
  • 17
1

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)
Robert Yi
  • 1,553
  • 1
  • 14
  • 18
-1

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))
EnGassa
  • 2,927
  • 1
  • 14
  • 16