简体   繁体   中英

Python3 - How to convert a string to hex

I am trying to convert a string to hex character by character, but I cant figure it out in Python3.

In older python versions, what I have below works:

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

But with python3 I am getting the following error:

LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs.

Can anyone help to tell me what the conversion would be in python3.

Thanks in advance

In python 3x Use binascii instead of hex:

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

To print:

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

To convert:

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

or without the '0x' in output:

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

How about:

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM