If you don't have problem with recursion approach then here is a solution with little change in your code:-
def get_digit(num):
if num < 10:
print(num)
else:
get_digit(num // 10)
print(num % 10)
Usage
>>> get_digit(543267)
5
4
3
2
6
7
Answer from AlokThakur on Stack OverflowIf you don't have problem with recursion approach then here is a solution with little change in your code:-
def get_digit(num):
if num < 10:
print(num)
else:
get_digit(num // 10)
print(num % 10)
Usage
>>> get_digit(543267)
5
4
3
2
6
7
Here is a generator which returns the digits of a positive integer in a left to right manner:
from math import floor, log10
def digits(n):
"""generator which returns digits in left to right order"""
k = floor(log10(n))
for e in range(k,-1,-1):
d,n = divmod(n,10**e)
yield d
For example,
>>> list(digits(2016))
[2, 0, 1, 6]
I'd use a regexp:
>>> import re
>>> re.findall(r'\d+', "hello 42 I'm a 32 string 30")
['42', '32', '30']
This would also match 42 from bla42bla. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b:
>>> re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")
['42', '32', '30']
To end up with a list of numbers instead of a list of strings:
>>> [int(s) for s in re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")]
[42, 32, 30]
NOTE: this does not work for negative integers
If you only want to extract only positive integers, try the following:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.
This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.