1

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?

5
  • Please explain your use case, there may be some better ways to achieve what you are trying to do Commented Oct 24, 2021 at 12:36
  • I have 5 different variable and need to update these in a table. Need to loop queryset to update this 5 variables by increasing a1,a2 like this. Commented Oct 24, 2021 at 12:39
  • Sorry, I don't quite understand your requirement. Why don't you edit your OP and explain things in a bit more detail? Someone might have a solution for you. Commented Oct 24, 2021 at 12:41
  • Looking at my code it seems valid question. Is there any option to arrive at variable by concatenating str and int? Or its not possible? Commented Oct 24, 2021 at 12:43
  • Storing your variables in a list or dict instead may be simpler Commented Oct 24, 2021 at 12:46

3 Answers 3

1

You can use python inbuilt function eval for such requirements like below :-

>> a1 = 10
>> b = "a"+"1"
>> print(eval(b))
>> 10
Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer. Thanks a lot. Wonderfully same eval() works in Javascript.
1

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

1 Comment

This is workaround. Correct answer is stackoverflow.com/a/69698328/6303199
0

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.

2 Comments

There is no way to arrive at variable? cant we convert it to variable?
@PulkitSharma you could make a list of those variables and loop it inside your function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.