1

A simple question that I'd like to incorporate into my program. I want to append the "variable" name to the "1", such that I eventually end with "variable1" as a single variable, as shown below.

variable1 = 55
j=1
print(varible+str(j))

I want the output to be 55. Is there a way to make this?

Thank you

albert
  • 27
  • 2
  • 3
    Do you want to make a lot of these? (e. g: variable1, variable2, variable3, ...). If so, consider using a list. – Alan Bagel Sep 08 '21 at 13:47
  • 1
    `globals()["variable" + str(j)]` but you most likely do not want to do that. Use a list or dictionary. – 001 Sep 08 '21 at 13:50
  • 2
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Ture Pålsson Sep 08 '21 at 13:55
  • `variable = [55]; j=0; print(variable[j])`. – chepner Sep 08 '21 at 14:00

3 Answers3

0

The easiest solution would be to define the variables inside a dictionary:

variables_dict = {}
variables_dict["variable1"]=55
variables_dict["variable23"]=812
variables_dict["david"]="abc"

Then you can access the different dictionary keys using strings so:

print(variables_dict["variable"+str(j)])

would work

Nir
  • 106
  • 1
  • 7
-1

Yes there is a method called eval but if you don't really really have to you should not use eval.

variable1 = 55
j=1
print(eval('variable'+str(j)))

A list or something else will probably solve your original problem

alparslan mimaroğlu
  • 1,450
  • 1
  • 10
  • 20
-1

Not sure if i understood your example correct. But maybe the f-string could be the solution. (https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python)

variable = 55
j = 1
print(f"variable{j}")

#if you want to add multiple numbers use a loop
for x in range(10):
    variable = 55
    print(f"variable{x}")
NH23
  • 1
  • 2