【问题标题】:python 3: string to hex, hex to formatpython 3:字符串转十六进制,十六进制转格式
【发布时间】:2012-08-15 11:21:59
【问题描述】:

问题:我需要将一个字符串转换成十六进制,然后格式化十六进制输出。

tmp = b"test"
test = binascii.hexlify(tmp)
print(test) 

输出:b'74657374'


我想将此十六进制输出格式化为如下所示:74:65:73:74

我遇到了障碍,不知道从哪里开始。我确实想过将输出再次转换为字符串,然后尝试对其进行格式化,但必须有更简单的方法。

任何帮助将不胜感激,谢谢。

===========

操作系统:Windows 7

tmp = "test"
hex = str(binascii.hexlify(tmp), 'ascii')
print(hex)

formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))
print(formatted_hex

[错误] 回溯(最近一次通话最后): 文件“C:\pkg\scripts\Hex\hex.py”,第 24 行,在 十六进制 = str(binascii.hexlify(tmp),'ascii') TypeError: 'str' 不支持缓冲区接口

此代码仅在使用 tmp = b'test' 时有效,我需要能够以时尚的方式使用 tmp = importString,因为我从文件顺序中将另一个值传递给它,以便我的 sn-p 工作。有什么想法吗?

【问题讨论】:

    标签: python-3.x hex


    【解决方案1】:

    此代码产生预期的输出:

    tmp='test'
    
    l=[hex(ord(_))[2:] for _ in tmp]
    
    print(*l,sep=':')
    

    -->74:65:73:74

    【讨论】:

      【解决方案2】:

      从 Python 3.8 开始,此功能在标准库中可用:binascii.hexlify 有一个新参数 sep

      test = binascii.hexlify(tmp, b':')
      

      如果您想要文本 (str) 字符串而不是 bytes 字符串:

      test = binascii.hexlify(tmp, b':').decode('ascii')
      

      【讨论】:

        【解决方案3】:
        >>> from itertools import izip_longest, islice
        >>> t = b"test".encode('hex')
        >>> ':'.join(x[0]+x[1] for x in izip_longest(islice(t,0,None,2),islice(t,1,None,2)))
        '74:65:73:74'
        

        【讨论】:

        • 很好,但请阅读问题。 “编码”在 python 3 中不起作用
        【解决方案4】:
        hex = str(binascii.hexlify(tmp), 'ascii')
        formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))
        

        这利用了range()step 参数,它指定不是给出范围内的每个整数,而是应该只给出每个第二个整数(对于step=2)。


        >>> tmp = "test"
        >>> import binascii
        >>> hex = str(binascii.hexlify(tmp), 'ascii')
        >>> formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))
        >>> formatted_hex
        '74:65:73:74'
        

        【讨论】:

        • 我正在使用 Windows 7,我得到这个错误 ysing 你的答案: Traceback(最近一次调用最后一次):文件“C:\pkg\scripts\py3\hex.py”,第 31 行, in formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2)) TypeError: sequence item 0: expected str instance, bytes found
        • 抱歉,我错过了一个str() 电话。
        • 没问题,你救了我一大堆在黑暗中跌跌撞撞的循环。 :) 谢谢。
        • Python 2.7.3 我得到:TypeError: str() 最多接受 1 个参数(给定 2 个),将其更改为 hex = sbinascii.hexlify(tmp) 并工作
        • @onxx 您可以通过bytes() 类型构造函数将字符串转换为字节。
        猜你喜欢
        • 1970-01-01
        • 2022-07-08
        • 1970-01-01
        • 2018-01-22
        • 2018-01-31
        • 2015-05-30
        • 2011-01-21
        • 1970-01-01
        • 2017-08-12
        相关资源
        最近更新 更多