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 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
  • 96
  • 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

-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