我想要将以字符串形式存储的MAC地址00163e2fbab7转换为其字符串表示形式00:16:3e:2f:ba:b7。最简单的方法是什么?
我想要将以字符串形式存储的MAC地址00163e2fbab7转换为其字符串表示形式00:16:3e:2f:ba:b7。最简单的方法是什么?
使用一种非常间接的方法来利用现有函数,该函数每次分组两个十六进制字符:
>>> ':'.join(s.encode('hex') for s in '00163e2fbab7'.decode('hex'))
'00:16:3e:2f:ba:b7'
已更新至Python 3:
>>> ':'.join(format(s, '02x') for s in bytes.fromhex('00163e2fbab7'))
'00:16:3e:2f:ba:b7'
使用 grouper 惯用法 zip(*[iter(s)]*n)
:
In [32]: addr = '00163e2fbab7'
In [33]: ':'.join(''.join(pair) for pair in zip(*[iter(addr)]*2))
Out[33]: '00:16:3e:2f:ba:b7'
也有另外一种可能性(事实上,速度稍微快一些):
In [36]: ':'.join(addr[i:i+2] for i in range(0,len(addr),2))
Out[36]: '00:16:3e:2f:ba:b7'
s
,想要用冒号进行连接,可以使用以下方法。':'.join([s[i]+s[i+1] for i in range(0,12,2)])
''.join(s[i:i+2])
。 - Michael Mior':'.join([s[i]+s[i+1] for i in range(0,12,2)])
时,它会给出与':'.join([s[i:i+2] for i in range(0,12,2)])
相同的结果。字符串切片不会返回一个数组。 - Steven Rumbalski>>> import re
>>> s = '00163e2fbab7'
>>> ':'.join(re.findall('..', s))
'00:16:3e:2f:ba:b7'
> 适用于 Python 3
ap_mac = b'\xfe\xdc\xba\xab\xcd\xef'
decoded_mac = hexlify(ap_mac).decode('ascii')
formatted_mac = re.sub(r'(.{2})(?!$)', r'\1:', decoded_mac)
def to_mac(addr: int, sep=':'):
return sep.join('{:02x}'.format(s) for s in bytes.fromhex('{:012x}'.format(addr)))
print(to_mac(0x1))
print(to_mac(0x12))
print(to_mac(0x123))
print(to_mac(0x1234))
print(to_mac(0x12345))
print(to_mac(0x123456))
print(to_mac(0x1234567))
print(to_mac(0x12345678))
print(to_mac(0x123456789))
print(to_mac(0x123456789A))
print(to_mac(0x123456789AB))
print(to_mac(0x123456789ABC, sep='-').upper())
00:00:00:00:00:01
00:00:00:00:00:12
00:00:00:00:01:23
00:00:00:00:12:34
00:00:00:01:23:45
00:00:00:12:34:56
00:00:01:23:45:67
00:00:12:34:56:78
00:01:23:45:67:89
00:12:34:56:78:9a
01:23:45:67:89:ab
12-34-56-78-9A-BC