I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the isdigit()
method?
Example:
I am amazed to see that no one has yet mentioned the usage of itertools.groupby as an alternative to achieve this.
You may use itertools.groupby() along with str.isdigit() in order to extract numbers from string as:
from itertools import groupby
my_str = "hello 12 hi 89"
l = [int(''.join(i)) for is_digit, i in groupby(my_str, str.isdigit) if is_digit]
The value hold by l
will be:
[12, 89]
PS: This is just for illustration purpose to show that as an alternative we could also use groupby
to achieve this. But this is not a recommended solution. If you want to achieve this, you should be using accepted answer of fmark based on using list comprehension with str.isdigit
as filter.