How to extract numbers from a string in Python?

后端 未结 17 2047
星月不相逢
星月不相逢 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:57

    I am just adding this answer because no one added one using Exception handling and because this also works for floats

    a = []
    line = "abcd 1234 efgh 56.78 ij"
    for word in line.split():
        try:
            a.append(float(word))
        except ValueError:
            pass
    print(a)
    

    Output :

    [1234.0, 56.78]
    

提交回复
热议问题