A
A
adambldor22020-07-19 15:09:46
Python
adambldor2, 2020-07-19 15:09:46

How to go from string to variable?

The question is: I form the name of a variable in a loop, but, of course, it is a string. I need to pass from a string to a variable so that when I use print, for example, the program prints out the value. Is it possible?

a1 = 1
a2 =2
for r in range(1,3):
    nm = 'a'+r
    print(nm)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dr. Bacon, 2020-07-19
@adambldor2

Don't do that, use a list or a dictionary. https://qna.habr.com/answer?answer_id=1502759#answ...

H
Hcuy, 2020-07-19
@Hcuy

How much understood it is necessary to add 'a' to numbers. If so then try this:

a = 123
a = list(str(a)) # Преобразуем в строку 'str', а потом в список 'list'
ln = len(a) # Получаем длину списка
for i in range(ln):
  a[i] = a[i] + 'a' #К каждому элементу списка добавляем нужную букву
print (a) # Выводим на монитор результат

0
0ralo, 2020-07-19
@0ralo

a1 = 1
a2 = 2
for r in range(1,3):
    exec(f"print(a{r})")

But it's better to never do that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question