Perform a substring replacement in a single line in Python
python, regex
Solution
>>> mac = '8:AA:C:3:ED:E'
>>> print ':'.join([i.zfill(2) for i in mac.split(':')])
08:AA:0C:03:ED:0E
To use it like a "standard library" with a "convenient interface":
>>> def fix_mac_adr(adr):
return ':'.join([i.zfill(2) for i in adr.split(':')])
>>> fix_mac_adr('8:AA:C:3:ED:E')
'08:AA:0C:03:ED:0E'
One-liner (from Mike DeSimone):
>>> fix_mac_adr = lambda adr: ':'.join([i.zfill(2) for i in adr.split(':')])
Problem
I'm reading in MAC addresses on my LAN using the `arp -a` command and parsing the output. On OS X, some MAC addresses are returned with hex values lacking leading zeros. I've figured out how to insert the leading zeros using regex: ``` >>> mac = '8:AA:C:3:ED:E' >>> mac = re.sub('^(?P<hex>.)(?=\:)','0\g<hex>',mac) >>> mac = re.sub('(?<=\:)(?P<hex>.)(?=\:)','0\g<hex>',mac) >>> mac = re.sub('(?<=\:)(?P<hex>.)$','0\g<hex>',mac) >>> print mac 08:AA:0C:03:ED:0E ``` This works, but I'm sure there's a way to perform a replacement in a single line for an arbitrary MAC address, where any hex value can potentially lack a leading zero...I just can't figure it out.