Converting all chars in a string to ascii hex in python

Question:

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 ‘x48x65x6cx6c’

Asked By: Echocage

||

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)
x48x65x6cx6cx6fx20x57x6fx72x6cx64
Answered By: mgilson

Try:

" ".join([hex(ord(x)) for x in myString])
Answered By: unwind

Something like:

>>> s = '123456'
>>> from binascii import hexlify
>>> hexlify(s)
'313233343536'
Answered By: Jon Clements

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'
Answered By: Jacky Yan

Starting from Python 3.5 you can use hex method to convert string to hex values (resulting in a string):

str = '1234'
str.encode().hex()
# '31323334'

Knowing that it’s possible to resolve it in yet another way:

str = '1234'
hexed = str.encode().hex()
hex_values = [hexed[i:i+2] for i in range(0, len(hexed), 2)] # every 2 chars
delim = r'x'

res = delim + delim.join(hex_values)
print(res)
# 'x31x32x33x34'

Note:
You can omit encode() method if you define your string as bytes: str = b'1234'.

Answered By: Urax
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.