How to extract numbers from a string in Python?



If you only want positive integers, you can split and search for numbers as follows:

>>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]

For all other cases, using a regular expression would be the best choice. Also when extracting values, it'll be best to convert them to ints from string. For example:

>>> import re
>>> [float(s) for s in re.findall(r'-?\d+\.?\d*', 'he33.45llo -42 I\'m a 32 string 30')]
[33.45, -42.0, 32.0, 30.0]

Advertisements