I have this string:
number = "0123456789"
I want to create variables that are iterative having values from the string. For example,
I want a string like
a1 =1,
a3=3,
...
a8=8
Please advise. Thank You
There is ambiguity in question. I address the following part: 'I want to create variables that are iterative having values from the string.'
If you solve problem of creating variables dynamically you have created a new problem - how to access them dynamically. Therefore it's much better to use some built-in datastrucuture like list, tuple or dictionary.
Keeping this in mind answer to the question:
number = '0123456789'
for num in number:
globals()[f'a{num}'] = int(num)
This code will create variables a0, a1...a9 with corresponding integer values.
To make an iterable object with indecies I do something like:
number = "0123456789"
new_number = ""
for i in number:
if i != number[-1]:
new_number += i + " "
else:
new_number += i
iterable = new_number.split(" ")
This could likely be made less messy if you are interested in that, but this does the trick. Note: the elements in the iterable will be strings.
You can loop through each character in your variable number but you have to typecast it to string. And please note that number=0123456789 will error in Python. You need a string value. So typecasting the numeric value to string will solve it.
Example:
number = str(123456789)
for i in number:
globals() ['a'+i] = int(i)
Then you can use the created variable as usual like this:
print(a1)
print(a9)
This will output:
1
9
I hope this answered your question.
a = [i for i in range(10)]).