IPv6 压缩地址格式转首选地址格式 python 2.7

#coding=utf-8
from __future__ import print_function
import sys

def bu0(dizhi):
    dizhi1 = dizhi.split(':')
    for i in range(0, len(dizhi1)):
        # 小段地址补0 如 :AB: 补成:00AB:
        if ((len(dizhi1[i]) < 4) and (len(dizhi1[i]) > 0)) :
            temp = dizhi1[i]
        # 需补0数 que0
            que0 = 4 - len(dizhi1[i])
            temp2 =  "".join('0' for i in range(0, que0))
            dizhi1[i] = temp2 + temp

    # 补 ::中的0
    # count 为补完:中0后长度
    count = 0
    for i in range(0, len(dizhi1)):
        count = count + len(dizhi1[i])
    count = 32 - count
    aa = []
    aa = ''.join('0' for i in range(0, count))
    for i in range(1, len(dizhi1)-1):
        if len(dizhi1[i])==0 :
            dizhi1[i] = aa
    for i in range(len(dizhi1)):
        bb = ''.join(sttt for sttt in dizhi1)
    return bb

def legal(dizhi):
    dizhi1 = dizhi.split('::')
    label = 1

    # 使用::不能大于2次
    if len(dizhi1) >= 3:
        label = 0
        print(":: times >2")
    else:

        # 字符范围应为 0~9 A~F
        for i,char in enumerate(dizhi):
            if char not in ':0123456789ABCDEF':
                print("char value not legal")
                label = 0
    # :不能出现在末位 同时允许::在最后
    # :不能出现在首位 同时允许::在最前
    if (dizhi[len(dizhi)-1]==':') and (dizhi[len(dizhi)-2]!=':') :
        label = 0
    if (dizhi[0]==':') and (dizhi[1]!=':') :
        label = 0
        print(": position not legal")

    # 不能出现 :::
    temp3 = dizhi.split(":::")
    if len(temp3) >1:
        print("::: not legal")
        label = 0

    # 每小节位数应不大于4
    dizhi2 = dizhi.split(':')
    for i in range(0, len(dizhi2)):
        if len(dizhi2[i]) >=5:
            print("每小节位数应不大于4")
            label = 0

    if label == 0:
        print("Error")
    return label

if __name__ == "__main__":
    a = sys.stdin.readline().strip()
    if legal(a):
        out = bu0(a)
        for i in range(0,32):
            print(out[i],sep='',end='')
            _, p = divmod(i+1, 4)
            if ((p == 0) and (i!=31)):
                print(':',sep='',end='')

# :a:
# :a
# ::A::A
# ::1
# 1::
# ::0
# :AB:C
# ABC::
# ABC:::AB
# ::A
# A::
# AAAAA::
# ABC:0835:9358::9581:0358:9385:3195

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值