最简单! Python判断ip地址是否格式正确

判断变量ip是否是正确的ip地址

def ip_identify(ip):
        try:
                iplist=ip.split(".")
        except AttributeError:
                return False
        try:
                if len(iplist)==4:
                        for i in iplist:
                                if not (int(i) <=255 and int(i) >=0):
                                        return False #ip格式错误
                        return True #ip
                else:
                        return False
        except ValueError:
                return False

用脚写的,不会正则表达式,不过测试了一些数据好像也没问题,凑合能用就行了

加了两个try

except AttributeError :解决了调用ip_identify(ip),ip为非字符串的问题

except ValueError: 解决了int(i) i不能正常转化为整数的问题

20210918

优化了一下

def ip_identify(ip):
    result=False
    try:
        iplist = ip.split(".")
        if len(iplist) == 4:
            check_count = 0
            for i in iplist:
                if not (int(i) <= 255 and int(i) >= 0):
                    break
                else:
                    check_count += 1
            if check_count == 4: result = True  # ip
    except Exception as e:
        pass
    finally:
        return result

直接捕获所有的异常,这样貌似更精确,

你可能感兴趣的:(python,字符串,正则表达式)