Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant Format for a MAC Address in Python 3.2

Tags:

python

I am looking for a more elegant solution to formatting a MAC address with colons. I am using Python 3.2. A fancy list comprehension perhaps?

s=""
h="00233a990c21"
for i in range(0,12,2):
    s += h[i:i+2] + ":"
s=s[:-1]
print("s=",s)
like image 424
jftuga Avatar asked Jun 13 '12 00:06

jftuga


3 Answers

Your code is easily converted to a comprehension form:

':'.join(h[i:i+2] for i in range(0,12,2))
like image 134
Lev Levitsky Avatar answered Nov 03 '22 10:11

Lev Levitsky


This is not the shortest solution, but it accepts all common types of mac formats as inputs. It also does some validation checks.

import re

def format_mac(mac: str) -> str:
    mac = re.sub('[.:-]', '', mac).lower()  # remove delimiters and convert to lower case
    mac = ''.join(mac.split())  # remove whitespaces
    assert len(mac) == 12  # length should be now exactly 12 (eg. 008041aefd7e)
    assert mac.isalnum()  # should only contain letters and numbers
    # convert mac in canonical form (eg. 00:80:41:ae:fd:7e)
    mac = ":".join(["%s" % (mac[i:i+2]) for i in range(0, 12, 2)])
    return mac

Here is a list of mac address strings and whether they will be considered as valid or invalid:

'008041aefd7e',  # valid
'00:80:41:ae:fd:7e',  # valid
'00:80:41:AE:FD:7E',  # valid
'00:80:41:aE:Fd:7E',  # valid
'00-80-41-ae-fd-7e',  # valid
'0080.41ae.fd7e',  # valid
'00 : 80 : 41 : ae : fd : 7e',  # valid
'  00:80:41:ae:fd:7e  ',  # valid
'00:80:41:ae:fd:7e\n\t',  # valid

'aa:00:80:41:ae:fd:7e',  # invalid
'0:80:41:ae:fd:7e',  # invalid
'ae:fd:7e',  # invalid
'$$:80:41:ae:fd:7e',  # invalid

All valid ones will be returned in the canonical form as:

'00:80:41:ae:fd:7e'
like image 6
Simon Schürg Avatar answered Nov 03 '22 08:11

Simon Schürg


from netaddr import EUI, mac_unix_expanded
print(EUI('00:01:02:03:04:05', dialect=mac_unix_expanded))
print(EUI('1-2-3-4-5-6', dialect=mac_unix_expanded))
like image 2
Derrick Avatar answered Nov 03 '22 09:11

Derrick