How to extract numbers from a string in Python?

后端 未结 17 1940
星月不相逢
星月不相逢 2020-11-21 05:19

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:

17条回答
  •  有刺的猬
    2020-11-21 05:53

    I'm assuming you want floats not just integers so I'd do something like this:

    l = []
    for t in s.split():
        try:
            l.append(float(t))
        except ValueError:
            pass
    

    Note that some of the other solutions posted here don't work with negative numbers:

    >>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string -30')
    ['42', '32', '30']
    
    >>> '-3'.isdigit()
    False
    

提交回复
热议问题