Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting all chars in a string to ascii hex in python

Tags:

python

ascii

Just looking for python code that can turn all chars from a normal string(all english alphbetic letters) to ascii hex in python. I'm not sure if I'm asking this in the wrong way because i've been searching for this but can't seem to find this.

I must just be passing over the answer, but i would love some help.

Just to clarify, from 'Hell' to '\x48\x65\x6c\x6c'

like image 813
Echocage Avatar asked Mar 08 '13 14:03

Echocage


4 Answers

I suppose ''.join(r'\x{02:x}'.format(ord(c)) for c in mystring) would 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
like image 76
mgilson Avatar answered Nov 18 '22 00:11

mgilson


Based on Jon Clements's answer, try the codes on python3.7. I have the error like this:

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

Solved by the following codes:

>>> str = '1234'.encode()    
>>> hexlify(str).decode()   
'31323334'
like image 41
Jacky Yan Avatar answered Nov 18 '22 01:11

Jacky Yan


Something like:

>>> s = '123456'
>>> from binascii import hexlify
>>> hexlify(s)
'313233343536'
like image 4
Jon Clements Avatar answered Nov 17 '22 23:11

Jon Clements


Try:

" ".join([hex(ord(x)) for x in myString])
like image 2
unwind Avatar answered Nov 18 '22 00:11

unwind