简单的python任务

时间:2016-02-11 19:52:02

标签: python python-2.7

基本上我需要用户输入ip地址。 我需要做的就是检查它是否有效(0-255; 4个八位字节)。 让我们说用户输入192.168.10.1, 如何将其分解为192,168,10,1?

5 个答案:

答案 0 :(得分:3)

这样做:

while True:
    ip = raw_input("Please enter an ip address")
    ip_split = ip.split(".")
    if len(ip_split) != 4:
        print "Must have 4 numbers"
    elif not all(number.isdigit() for number in ip_split):
        print "Must be numbers"
    elif not all(0 <= int(number) <= 255 for number in ip_split):
        print "Numbers must be in 0-255 range"
    else:
        ips = [int(number) for number in ip_split]
        break

答案 1 :(得分:1)

您可以使用split方法:

 your_string.split(separator)

在你的情况下:

 ip = "191.168.10.1"
 values_list = ip.split(".")

答案 2 :(得分:0)

我有这2个正则表达式来检查这个

import re

ip4 = re.compile(r'^(?:(?:25[0-5]|2[0-4]\d|1\d\d|\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|\d?\d)$')
ip6 = re.compile(r'^(?:[\da-fA-F]{1,4}:){7}[\da-fA-F]{1,4}$')

答案 3 :(得分:0)

您可以通过多种方式完成此操作。这可能是一个解决方案:

ip = "192.168.10.666"
octates = ip.split('.',4)

flag = True
for each_octate in octates:
    num = int(each_octate)
    if num>=0 and num<=255:
        continue
    else:
        flag = False
        break

if flag == True:
    print "IP is correct!"
else:
    print "IP is incorrect"

答案 4 :(得分:0)

你可以把ip地址作为一个字符串,然后从那里将str拆分为“。”然后检查每个成员的标准。

ip = input("Enter Ip address: ")
address = ip.split('.')
if len(address) == 4:
     for num in address:
          if 255 >= num >= 0:
               pass
          else:
               print("Invalid Ip Address!")
else:
     print("Invalid Ip Address!")