1

How can I format a hex string ('003de70fc98a') to a MAC string ('00:3d:e7:0f:c9:8a') using a concise statement?

Bruce
  • 31,811
  • 70
  • 170
  • 259
  • I know I have to use the format method of Python but I don't know how. I want a small crisp statement without a for loop etc. – Bruce Mar 17 '13 at 01:58
  • http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format , http://docs.python.org/library/string.html – Mitch Wheat Mar 17 '13 at 01:59

3 Answers3

4

You could use a regex:

>>> re.sub(r'(?<=..)(..)', r':\1', '003de70fc98a')
'00:3d:e7:0f:c9:8a'
FatalError
  • 50,375
  • 14
  • 97
  • 115
3
In [104]: hexstr = '003de70fc98a'

In [105]: ':'.join([hexstr[i:i+2] for i in range(0, len(hexstr), 2)])
Out[105]: '00:3d:e7:0f:c9:8a'

or,

In [108]: ':'.join(map(''.join, zip(*[iter(hexstr)]*2)))
Out[108]: '00:3d:e7:0f:c9:8a'
unutbu
  • 777,569
  • 165
  • 1,697
  • 1,613
1

Try this:

s = '003de70fc98a'
':'.join(s[i]+s[i+1] for i in range(0, len(s), 2))
=> '00:3d:e7:0f:c9:8a'
Óscar López
  • 225,348
  • 35
  • 301
  • 374