Python 3.1.1 string to hex

前端 未结 9 913
野的像风
野的像风 2020-11-28 04:59

I am trying to use str.encode() but I get

>>> \"hello\".encode(hex)
Traceback (most recent call last):
  File \"\", line 1         


        
9条回答
  •  独厮守ぢ
    2020-11-28 05:43

    In Python 3, all strings are unicode. Usually, if you encode an unicode object to a string, you use .encode('TEXT_ENCODING'), since hex is not a text encoding, you should use codecs.encode() to handle arbitrary codecs. For example:

    >>>> "hello".encode('hex')
    LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
    >>>> import codecs
    >>>> codecs.encode(b"hello", 'hex')
    b'68656c6c6f'
    

    Again, since "hello" is unicode, you need to indicate it as a byte string before encoding to hexadecimal. This may be more inline with what your original approach of using the encode method.

    The differences between binascii.hexlify and codecs.encode are as follow:

    • binascii.hexlify

      Hexadecimal representation of binary data.

      The return value is a bytes object.

      Type: builtin_function_or_method

    • codecs.encode

      encode(obj, [encoding[,errors]]) -> object

      Encodes obj using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a ValueError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle ValueErrors.

      Type: builtin_function_or_method

提交回复
热议问题