How to extract numbers from a string in Python?

后端 未结 17 2045
星月不相逢
星月不相逢 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:54

    The best option I found is below. It will extract a number and can eliminate any type of char.

    def extract_nbr(input_str):
        if input_str is None or input_str == '':
            return 0
    
        out_number = ''
        for ele in input_str:
            if ele.isdigit():
                out_number += ele
        return float(out_number)    
    

提交回复
热议问题