How to extract numbers from a string in Python?

后端 未结 17 2091
星月不相逢
星月不相逢 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 06:00

    # extract numbers from garbage string:
    s = '12//n,_@#$%3.14kjlw0xdadfackvj1.6e-19&*ghn334'
    newstr = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in s)
    listOfNumbers = [float(i) for i in newstr.split()]
    print(listOfNumbers)
    [12.0, 3.14, 0.0, 1.6e-19, 334.0]
    

提交回复
热议问题