Apollo
Apollo

Reputation: 9064

Iterate over digits of number

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: 47041

Answers (2)

Kasravnd
Kasravnd

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

user2555451
user2555451

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

Related Questions