Home > Mobile >  Django: How to convert string and int into variable
Django: How to convert string and int into variable

Time:10-24

I have declared a variable as"

a1 = 10

Now in a function I need to call this variable by adding "a" "1". However result is a1 in string and not above declared variable.

Here is the code:

a1 = 10
b = "a" "1"
print(b)
a1

when I print b, answer is a1, instead of 10. How can I change this concatenate to declared variable?

CodePudding user response:

The statement b = 'a' '1' means that your new variable b is a string:

>>> b = ['a1']

If you are interested in printing a1, you have just to do:

print(a1)

Making a sum of the letters of a declared variable does not result in the variable itself.

CodePudding user response:

if I understand, you want to dynamically create the name of a variable and access it : you can use dict for that i think

a1, a2, a3 = 10, 11, 12
var_dict = {'a1': a1, 'a2': a2, 'a3': a3}

for i in [1, 2, 3]:
    print(var_dict[f"a{i}"])  # f"a{i}" => 'a1', 'a2', 'a3' according to i value
  • Related