Convert all characters in a string to ascii hex in python

Just find python code that can turn all characters from a regular string (all English letters of the alphabet) into ascii hex in python. I am not sure what I am asking about this is wrong, because I was looking for it, but I can not find it.

I should just pass on the answer, but I would like to help.

To clarify, from "Hell" to "\ x48 \ x65 \ x6c \ x6c"

+7
source share
4 answers

I believe that ''.join(r'\x{02:x}'.format(ord(c)) for c in mystring)will do the trick ...

>>> mystring = "Hello World"
>>> print ''.join(r'\x{02:x}'.format(ord(c)) for c in mystring)
\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64
+5
source

Sort of:

>>> s = '123456'
>>> from binascii import hexlify
>>> hexlify(s)
'313233343536'
+4
source

Try:

" ".join([hex(ord(x)) for x in myString])
+1
source

Based on John Clement's answer, try the python3.7 codes. I have this error:

>>> s = '1234'    
>>> hexlify(s)    
Traceback (most recent call last):    
  File "<pyshell#13>", line 1, in <module>    
    hexlify(s)    
TypeError: a bytes-like object is required, not 'str'

It is solved by the following codes:

>>> str = '1234'.encode()    
>>> hexlify(str).decode()   
'31323334'
0
source

All Articles