题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
需要考虑的场景比较多;
本人将ipv4与ipv6分开考虑处理;
用split('.')将字符串转化成列表进行判断
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 验证IP地址 # @param IP string字符串 一个IP地址字符串 # @return string字符串 # class Solution: def solve(self , IP: str) -> str: # write code here # 构造一个16进制的字符串备用 v6 = '0123456789abcdef' if IP.count('.') >0 and IP.count(':')>0: return 'Neither' elif IP.count('.') >0 and not IP.count(':'): IPv4 = IP.split('.') # print(IPv4) if len(IPv4) != 4: return 'Neither' else: if IPv4[0] == '0': return 'Neither' else: for i in IPv4: if not i.isnumeric(): return 'Neither' if not i : return 'Neither' if int(i) < 0 or int(i) > 255: return 'Neither' else: if len(i) > 1 and i[0] == '0': return 'Neither' # else: return 'IPv4' elif not IP.count('.') and IP.count(':') > 0: if len(IP) > 50: return 'Neither' IP = IP.lower() IPv6 = IP.split(':') if len(IPv6) != 8: return 'Neither' else: for i in IPv6: if not i: return 'Neither' for j in i: if j not in v6: return 'Neither' if len(i) > 1 and i[0] == '0' and i[1] == '0': return 'Neither' return 'IPv6' else: return 'Neither'