1

I know I could use arrays and then this problem could be solved easily.

But I'm curious if there's another solution for my problem. I want to reproduce my variables (var1, var2, var3) inside the print function by concatenating "var" + x (1,2,3)

var1 = "one"
var2 = "two"
var3 = "three"

for x in range(1, 4):

    print ("var" + "%d" % (x))

desired output result:

one
two
three

What I get as a result is:

var1
var2
var3
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
Barna96
  • 15
  • 6

3 Answers3

4

you can use locals() to get a dict mapping local variable names to their values, and then accessing it by the name as your code tries:

var1 = "one"
var2 = "two"
var3 = "three"

for x in range(1, 4):

    print (locals()["var" + "%d" % (x)])
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
1

You could use vars() to obtain a dictionary of the defined variables in the current module.

var1 = "one"
var2 = "two"
var3 = "three"

for x in range(1, 4):
    print (vars()["var" + "%d" % (x)])
Manuel Otto
  • 6,410
  • 1
  • 18
  • 25
0

You can use eval()

for x in range(1,4):
    print(eval("var"+str(x)))

However this can only be used for variable names that have a known pattern. Otherwise you need to take a look here

Teshan Shanuka J
  • 1,448
  • 2
  • 17
  • 31
  • Please don't suggest using eval to such a basic question. There are better, more pythonic ways... :) – Oerd Jun 13 '19 at 14:25
  • Of course using `eval()` has its own problems. But I don't see what is wrong with using `eval()` in this specific problem. There are always more than one way to do something in python. How do you say using `eval()` is less "pythonic"? – Teshan Shanuka J Jun 13 '19 at 14:35
  • Have a look at the two answers using `vars()` and `locals()` – Oerd Jun 13 '19 at 14:41
  • Yes I saw them. They work just as fine as this solution. However `eval()` will be slower compared to them. You should not use `eval` such that it can be a security exploit (e.g. with `input`). I don't see such a problem here – Teshan Shanuka J Jun 13 '19 at 14:46