Python 3.1.1 string to hex

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

    Yet another method:

    s = 'hello'
    
    h = ''.join([hex(ord(i)) for i in s]);
    
    # outputs: '0x680x650x6c0x6c0x6f'
    

    This basically splits the string into chars, does the conversion through hex(ord(char)), and joins the chars back together. In case you want the result without the prefix 0x then do:

    h = ''.join([str(hex(ord(i)))[2:4] for i in s]);
    
    # outputs: '68656c6c6f'
    

    Tested with Python 3.5.3.

提交回复
热议问题