蟒蛇.打印6字节字符串中的mac地址

PSS*_*PSS 6 python printing tcp

我有6字节字符串的mac地址.你会如何以"人类"可读格式打印它?

谢谢

Jir*_*iri 9

import struct
"%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",your_variable_with_mac)
Run Code Online (Sandbox Code Playgroud)

  • %02x好一点 (4认同)
  • 您可能应该使用“%02x”而不是“%x”。否则,对于低于 *16* 的字节,前面的 *0* 会丢失。 (2认同)

Sco*_*ths 9

没有必要使用struct:

def prettify(mac_string):
    return ':'.join('%02x' % ord(b) for b in mac_string)
Run Code Online (Sandbox Code Playgroud)

虽然if mac_stringbytearray(或bytes在Python 3中),这是一个比给定数据性质的字符串更自然的选择,那么你也不需要该ord函数.

用法示例:

>>> prettify(b'5e\x21\x00r3')
'35:65:21:00:72:33'
Run Code Online (Sandbox Code Playgroud)

  • 我发现 `b.encode('hex')` 比 `'%02x' % ord(b)` 更具可读性,但效果是相同的。 (2认同)

Joj*_*GME 9

Python 3.8及更高版本中,您可以只使用bytes.hex.

b'\x85n:\xfaGk'.hex(":") // -> '85:6e:3a:fa:47:6b'
Run Code Online (Sandbox Code Playgroud)