Python: Determine whether a string is an integer or floating point number

1. The method is flawed: if it is an empty string, the returned value is also True, which should be judged as True in the second try

def is_number(num):
        try:  # 如果能运行float(s)语句,返回True(字符串s是浮点数)
            float(num)
            return True
        except ValueError:  # ValueError为Python的一种标准异常,表示"传入无效的参数"
            pass  # 如果引发了ValueError这种异常,不做任何事情(pass:不做任何事情,一般用做占位语句)
        try:
            import unicodedata  # 处理ASCii码的包
            for i in num:
                unicodedata.numeric(i)  # 把一个表示数字的字符串转换为浮点数返回的函数
                return True
            return True
        except (TypeError, ValueError):
            pass
        return False

Two, can judge integers, floating point numbers

    def is_number(num):
        s = str(num)
        if s.count('.') == 1:  # 小数
            new_s = s.split('.')
            left_num = new_s[0]
            right_num = new_s[1]
            if right_num.isdigit():
                if left_num.isdigit():
                    return True
                elif left_num.count('-') == 1 and left_num.startswith('-'):  # 负小数
                    tmp_num = left_num.split('-')[-1]
                    if tmp_num.isdigit():
                        return True
        elif s.count(".") == 0:  # 整数
            if s.isdigit():
                return True
            elif s.count('-') == 1 and s.startswith('-'):  # 负整数
                ss = s.split('-')[-1]
                if ss.isdigit():
                    return True
        return False

 

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/108540915