I would like to extract all the numbers contained in a string. Which is better suited for the purpose, regular expressions or the isdigit()
method?
Example:
line = "hello 12 hi 89"
Result:
[12, 89]
I would like to extract all the numbers contained in a string. Which is better suited for the purpose, regular expressions or the isdigit()
method?
Example:
line = "hello 12 hi 89"
Result:
[12, 89]
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]