Reputation: 9064
I have a string input, such as 100124
. I want to evaluate each digit of the string as an integer, so I do:
for c in string:
c = int(c)
# do stuff with c
Is there a syntactically better way to do this? I tried doing string = int(string)
before the loop, but a number isn't iterable.
Upvotes: 17
Views: 47042
Reputation: 107357
You can use a list comprehension that return a generator :
>>> [int(i) for i in s]
[1, 0, 0, 1, 2, 4]
>>> for digit in [int(i) for i in s] :
... # do stuff with digit
or map
function :
>>> map(int,s)
[1, 0, 0, 1, 2, 4]
Upvotes: 3
Reputation:
You could map
the string to int
:
for c in map(int, string):
# do stuff with c
Demo:
>>> for c in map(int, '100124'):
... c
...
1
0
0
1
2
4
>>>
Upvotes: 23