How do I parse a string to a float or int?

后端 未结 29 2804
醉话见心
醉话见心 2020-11-21 04:43

In Python, how can I parse a numeric string like \"545.2222\" to its corresponding float value, 545.2222? Or parse the string \"31\" t

29条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 05:02

    This is a function which will convert any object (not just str) to int or float, based on if the actual string supplied looks like int or float. Further if it's an object which has both __float and __int__ methods, it defaults to using __float__

    def conv_to_num(x, num_type='asis'):
        '''Converts an object to a number if possible.
        num_type: int, float, 'asis'
        Defaults to floating point in case of ambiguity.
        '''
        import numbers
    
        is_num, is_str, is_other = [False]*3
    
        if isinstance(x, numbers.Number):
            is_num = True
        elif isinstance(x, str):
            is_str = True
    
        is_other = not any([is_num, is_str])
    
        if is_num:
            res = x
        elif is_str:
            is_float, is_int, is_char = [False]*3
            try:
                res = float(x)
                if '.' in x:
                    is_float = True
                else:
                    is_int = True
            except ValueError:
                res = x
                is_char = True
    
        else:
            if num_type == 'asis':
                funcs = [int, float]
            else:
                funcs = [num_type]
    
            for func in funcs:
                try:
                    res = func(x)
                    break
                except TypeError:
                    continue
            else:
                res = x
    

提交回复
热议问题