As others have said, you have a semantic problem in your indentation, but you don't need to write such a function for this, a more Putin way to do this:
def get_digits(text): return filter(str.isdigit, text)
In the interpreter:
>>> filter(str.isdigit, "lol123") '123'
Some recommendations
Always test things when people show βfasterβ methods:
from timeit import Timer def get_digits1(text): c = "" for i in text: if i.isdigit(): c += i return c def get_digits2(text): return filter(str.isdigit, text) def get_digits3(text): return ''.join(c for c in text if c.isdigit()) if __name__ == '__main__': count = 5000000 t = Timer("get_digits1('abcdef123456789ghijklmnopq123456789')", "from __main__ import get_digits1") print t.timeit(number=count) t = Timer("get_digits2('abcdef123456789ghijklmnopq123456789')", "from __main__ import get_digits2") print t.timeit(number=count) t = Timer("get_digits3('abcdef123456789ghijklmnopq123456789')", "from __main__ import get_digits3") print t.timeit(number=count) ~
Tarantula
source share