1

I am trying to assign every letter in the given word 'cmpny' to an undefined variable(here, i am using counters as variable)

var_counter = 0
user_input = 'cmpny'
for usr in user_input:
    var_counter = var_counter + 1
    (var_counter_'%d' %var_counter) = usr
    print(var_counter'%d'%var_counter)

Here, I want this to appear as follows:

var_counter_1 = c
var_counter_2 = m
var_counter_3 = p
var_counter_4 = n
var_counter_5 = y

Is this possible?

1
  • Please check the answer Commented Dec 24, 2019 at 7:20

1 Answer 1

1

Try the following:

var_counter = 0
user_input = 'cmpny'

for usr in user_input:
  var_counter +=1
  tempVar = "var_counter_"+str(var_counter)
  globals()[tempVar] = usr

It will create variables like var_counter_1,var_counter_2,....

You can check the output by using:

print(var_counter_1)
print(var_counter_2) and so on

or by using loop

for i in range(1,len(user_input)+1):
   print(eval("var_counter_"+str(i)))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.