How can I format a hex string ('003de70fc98a') to a MAC string ('00:3d:e7:0f:c9:8a') using a concise statement?
Asked
Active
Viewed 1,830 times
1
-
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 Answers
4
You could use a regex:
>>> re.sub(r'(?<=..)(..)', r':\1', '003de70fc98a')
'00:3d:e7:0f:c9:8a'

FatalError
- 52,695
- 14
- 99
- 116
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
- 842,883
- 184
- 1,785
- 1,677
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
- 232,561
- 37
- 312
- 386