How to extract numbers from a string in Python?

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

    line2 = "hello 12 hi 89"
    temp1 = re.findall(r'\d+', line2) # through regular expression
    res2 = list(map(int, temp1))
    print(res2)
    

    Hi ,

    you can search all the integers in the string through digit by using findall expression .

    In the second step create a list res2 and add the digits found in string to this list

    hope this helps

    Regards, Diwakar Sharma

提交回复
热议问题