468,305 Members | 1,475 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,305 developers. It's quick & easy.

putting a string in Mac Address form

I came up with this. Is there a better (more pythonic) way to do it?

import string
def mac_to_norm(mac):
def bad_char(char):
if char not in string.hexdigits:
return False
return True
mac = filter(bad_char,mac)
if len(mac) is not 12: return None
new_mac = ''
c = 0
while len(new_mac) < 16:
new_mac += mac[c:c+2] + ':'
c=c+2
return new_mac[:-1].upper()
print mac_to_norm('0012.ab23.b2cd')
#shows: 00:12:AB:23:B2:CD

The part I think is bad is the while loop part. Could it be better?

Oct 31 '05 #1
1 1731
kyle.tk <ky*****@gmail.com> wrote:
...
new_mac = ''
c = 0
while len(new_mac) < 16:
new_mac += mac[c:c+2] + ':'
c=c+2
return new_mac[:-1].upper() ... The part I think is bad is the while loop part. Could it be better?


What about replacing this whole block with, say...:

return ':'.join(mac[c:c+2] for c in range(0, 12, 2)).upper()

(as you did already check that len(mac) is 12...)
Alex
Oct 31 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by songkv | last post: by
12 posts views Thread by James Norton-Jones | last post: by
5 posts views Thread by Olly | last post: by
1 post views Thread by Xh | last post: by
reply views Thread by NPC403 | last post: by
reply views Thread by Teichintx | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.