[英]Parsing a MAC address with python
如何将十六进制值“0000.0012.13a4”转换为“00:00:00:12:13:A4”?
text = '0000.0012.13a4'
text = text.replace('.', '').upper() # a little pre-processing
# chunk into groups of 2 and re-join
out = ':'.join([text[i : i + 2] for i in range(0, len(text), 2)])
print(out)
00:00:00:12:13:A4
import re
old_string = "0000.0012.13a4"
new_string = ':'.join(s for s in re.split(r"(\w{2})", old_string.upper()) if s.isalnum())
print(new_string)
OUTPUT
> python3 test.py
00:00:00:12:13:A4
>
无需修改,此方法可以处理您可能遇到的其他一些 MAC 格式,例如"00-00-00-12-13-a4"
试试下面的代码
import re
hx = '0000.0012.13a4'.replace('.','')
print(':'.join(re.findall('..', hx)))
Output: 00:00:00:12:13:a4
有一个非常简单的三步解决方案:
step1 = hexStrBad.replace('.','')
step2 = step1[0:2] + ':' + step1[2:4] + ':' + step1[4:6] + ':' + step1[6:8] + ':' + step1[8:10] + ':' + step1[10:12]
step3 = step2.upper()
它不是最漂亮的,但它会做你需要的!
目前还不清楚你到底在问什么,但如果你想要的只是让一个字符串全部大写,请使用.upper()
尝试稍微澄清一下您的问题,因为如果您询问将一些格式奇怪的字符串转换为看起来像 MAC 地址的内容,我们需要知道这一点才能回答您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.