How to convert MAC number to MAC string?

I want to convert the MAC address 00163e2fbab7 (saved as a string) to its string representation 00: 16: 3e: 2f: ba: b7. What is the easiest way to do this?

+5
source share
5 answers

Use a completely workaround method to take advantage of an existing function that groups two hexadecimal characters at a time:

>>> ':'.join(s.encode('hex') for s in '00163e2fbab7'.decode('hex'))
'00:16:3e:2f:ba:b7'

Updated for Python 3:

>>> ':'.join(format(s, '02x') for s in bytes.fromhex('00163e2fbab7'))
'00:16:3e:2f:ba:b7'
+22
source

Using the orgar idiom 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'

It is also possible (and essentially a little faster):

In [36]: ':'.join(addr[i:i+2] for i in range(0,len(addr),2))
Out[36]: '00:16:3e:2f:ba:b7'
+10
source

s, , .

':'.join([s[i]+s[i+1] for i in range(0,12,2)])
+5

, :

>>> import re
>>> s = '00163e2fbab7'
>>> ':'.join(re.findall('..', s))
'00:16:3e:2f:ba:b7'
+4

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)
0

All Articles