【问题标题】:Python3 - How to convert a string to hexPython3 - 如何将字符串转换为十六进制
【发布时间】:2016-08-12 03:42:13
【问题描述】:

我正在尝试将字符串逐个字符转换为十六进制字符,但在 Python3 中我无法弄清楚。

在较旧的 python 版本中,我下面的工作:

test = "This is a test"
for c in range(0, len(test) ):
   print( "0x%s"%string_value[i].encode("hex") )

但是使用 python3 我收到以下错误:

LookupError: 'hex' 不是文本编码;使用 codecs.encode() 处理任意编解码器。

谁能帮我告诉我在 python3 中的转换是什么。

提前致谢

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    在 python 3x 中使用binascii 而不是十六进制:

    >>> import binascii
    >>> binascii.hexlify(b'< character / string>')
    

    【讨论】:

      【解决方案2】:

      打印:

      for c in test:
          print(hex(ord(c)))
      

      转换:

      output = ''.join(hex(ord(c)) for c in test)
      

      或者在输出中没有“0x”:

      output = ''.join(hex(ord(c))[2:] for c in test)
      

      【讨论】:

        【解决方案3】:

        怎么样:

        >>> test = "This is a test"    
        >>> for c in range(0, len(test) ):
        ...     print( "0x%x"%ord(test[c]))
        ... 
        0x54
        0x68
        0x69
        0x73
        0x20
        0x69
        0x73
        0x20
        0x61
        0x20
        0x74
        0x65
        0x73
        0x74
        

        【讨论】:

          猜你喜欢
          • 2013-02-07
          • 2021-06-24
          • 2017-08-23
          • 2014-03-19
          • 2011-08-25
          • 2014-04-28
          • 2018-01-31
          • 2018-01-22
          相关资源
          最近更新 更多