As the comments on that answer note, in Python 3, filter
returns a filter generator object, so you must iterate over it and build a new string before you can call int
:
>>> s = '3 reviews'
>>> filter(str.isdigit, s)
<filter object at 0x800ad5f98>
>>> int(''.join(filter(str.isdigit, s)))
3
However, as other answers in that same thread point out, this is not necessarily a good way to do the job at all:
>>> s = '3 reviews in 12 hours'
>>> int(''.join(filter(str.isdigit, s)))
312
It might be better to use a regular expression matcher to find the number at the front of the string. You can then decide whether to allow signs (+
and -
) and leading white-space:
>>> import re
>>> m = re.match(r'\s*([-+])?\d+', s)
>>> m
<_sre.SRE_Match object; span=(0, 1), match='3'>
>>> m.group()
'3'
>>> int(m.group())
3
Now if your string contains a malformed number, m
will be None, and if it contains a sign, the sign is allowed:
>>> m = re.match(r'\s*([-+])?\d+', 'not a number')
>>> print(m)
None
>>> m = re.match(r'\s*([-+])?\d+', ' -42')
>>> m
<_sre.SRE_Match object; span=(0, 5), match=' -42'>
>>> int(m.group())
-42
If you wish to inspect what came after the number, if anything, add more to the regular expression (including some parentheses for grouping) and use m.group(1)
to get the matched number. Replace \d+
with \d*
to allow an empty number-match, if that's meaningful (but then be mindful of matching a lone -
or +
sign, if you still allow signs).