最简单! Python判断ip地址是否格式正确
判断变量ip是否是正确的ip地址def ip_identify(ip):iplist=ip.split(".")if len(iplist)==4:for i in iplist:if not (int(i) <=255 and int(i) >=0):return False #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
直接捕获所有的异常,这样貌似更精确,

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)