extract digits in a simple way from a python string [duplicate]

The simplest way to extract a number from a string is to use regular expressions and findall.

>>> import re
>>> s="300 gm"
>>> re.findall('\d+', s)
['300']
>>> s="300 gm 200 kgm some more stuff a number: 439843"
>>> re.findall('\d+', s)
['300', '200', '439843']

It might be that you need something more complex, but this is a good first step.

Note that you’ll still have to call int on the result to get a proper numeric type (rather than another string):

>>> map(int, re.findall('\d+', s))
[300, 200, 439843]

Leave a Comment