Python 3.1.1 string to hex

前端 未结 9 915
野的像风
野的像风 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:48

    Use hexlify - http://epydoc.sourceforge.net/stdlib/binascii-module.html

    0 讨论(0)
  • 2020-11-28 05:55

    In Python 3.5+, encode the string to bytes and use the hex() method, returning a string.

    s = "hello".encode("utf-8").hex()
    s
    # '68656c6c6f'
    

    Optionally convert the string back to bytes:

    b = bytes(s, "utf-8")
    b
    # b'68656c6c6f'
    
    0 讨论(0)
  • 2020-11-28 05:58

    binascii methodes are easier by the way

    >>> import binascii
    >>> x=b'test'
    >>> x=binascii.hexlify(x)
    >>> x
    b'74657374'
    >>> y=str(x,'ascii')
    >>> y
    '74657374'
    >>> x=binascii.unhexlify(x)
    >>> x
    b'test'
    >>> y=str(x,'ascii')
    >>> y
    'test'
    

    Hope it helps. :)

    0 讨论(0)
提交回复
热议问题