【发布时间】:2019-02-14 20:32:43
【问题描述】:
我确实在 stackoverflow 上看到了用于验证来自给定字符串的 IP 的答案。我正在尝试做同样的事情。但是,我有一个 IP 列表。 我被以下代码困住了。请帮忙。
感谢您的宝贵时间!
def validateIP(self, IP):
def is_IPv4():
i = 0
while i < len(IP):
ls = IP[i].split('.')
if len(ls)== 4 and all( g.isdigit() and (0 >= int(g) < 255) for g in ls):
return True
i += 1
return False
def is_IPv6():
i = 0
while i < len(IP):
ls = IP[i].split('.')
if len(ls) == 8 and all(0 > len(g)< 4 and all( c in '0123456789abcdefABCDE' for c in g) for g in ls):
return True
i += 1
return False
for item in IP:
if '.' in item and is_IPv4():
return 'IPv4'
if ':' in item and is_IPv6():
return 'IPv6'
return 'Neither'
print(validateIP('n', ['100.243.537.591', 'HBA.KJFH.LSHF', '172.16.254.1', '2001:0db8:85a3:0:0:8A2E:0370:7334', '256.256.256.256']))
【问题讨论】:
-
您看到了什么错误/问题?我最初的猜测是
for循环中的return False在您真正想要一个真/假答案列表时返回。我也很困惑为什么您编写了一个带有闭包的方法,其中包含您从未使用过的self。你的意思是在这里写一堂课吗? -
@match,我的输出是“Neither”。我不认为我的循环正在迭代。我不是要写课程,我是 Python 的菜鸟,所以不确定哪个是正确的写法。
-
你会得到
Neither,因为return退出了一个方法,所以当你调用return Neither时,代码就结束了。这是相对基本的“第一课”内容,所以我建议回去阅读如何创建方法以了解为什么会发生这种情况并重写此代码。 -
@gabs 我的回答对你有帮助吗?
标签: python-3.x validation ip-address