Python : 문자열이 정수인지 부동 소수점 숫자인지 확인

1. 메서드에 결함이 있습니다. 빈 문자열이면 반환 된 값도 True이므로 두 번째 시도에서 True로 판단해야합니다.

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

둘째, 정수, 부동 소수점 수를 판단 할 수 있습니다.

    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

 

추천

출처blog.csdn.net/weixin_38676276/article/details/108540915