A slightly simpler solution (python 2 only):
>>> "7061756c".decode("hex")
'paul'
Answer from cjm on Stack OverflowConverting all chars in a string to ascii hex in python - Stack Overflow
Converting string to ASCII HEX Python 3
Text to ASCII HEX via python?
How to convert a full ascii string to hex in python? - Stack Overflow
Videos
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
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'
Hi all,
I've been struggling with this for an hour or so, I'm trying to take a string such as
'Hell' to '\x48\x65\x6c\x6c'
For what I'm doing, I require the \x before the ascii hex
This is a dated solution from StackOverflow, that doesn't work on Python3
>>> 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 My new solution goes like this:
mystring = b'hello world'
#convert to hex
mystring = hexlify(mystring)
mystring = mystring.decode('ascii')
# hex, like this 68656c6c6f20776f726c64
#add in the \x in the right spots
mystring = '\\x'.join(mystring[i:i + 2] for i in range(-2, len(mystring), 2))
#looks like this at this point \x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64
#I need it back into the "b" format, so I encode it
mystring=mystring.encode(ascii)
# This breaks everything, now it becomes:
# b'\\x68\\x65\\x6c\\x6c\\x6f\\x20\\x77\\x6f\\x72\\x6c\\x64'
# I specifically can't use the double backslashes.Any ideas how to fix this or am I going about this all wrong? Thanks
You can encode()the string:
string = "{'id':'other_aud1_aud2','kW':15}"
h = hexlify(string.encode())
print(h.decode())
# 7b276964273a276f746865725f617564315f61756432272c276b57273a31357d
s = unhexlify(hex).decode()
print(s)
# {'id':'other_aud1_aud2','kW':15}
The tricky bit here is that a Python 3 string is a sequence of Unicode characters, which is not the same as a sequence of ASCII characters.
In Python2, the
strtype and thebytestype are synonyms, and there is a separate type,unicode, that represents a sequence of Unicode characters. This makes it something of a mystery, if you have a string: is it a sequence of bytes, or is it a sequence of characters in some character-set?In Python3,
strnow meansunicodeand we usebytesfor what used to bestr. Given a string—a sequence of Unicode characters—we useencodeto convert it to some byte-sequence that can represent it, if there is such a sequence:>>> 'hello'.encode('ascii') b'hello' >>> 'sch\N{latin small letter o with diaeresis}n' 'schön' >>> 'sch\N{latin small letter o with diaeresis}n'.encode('utf-8') b'sch\xc3\xb6n'but:
>>> 'sch\N{latin small letter o with diaeresis}n'.encode('ascii') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 3: ordinal not in range(128)
Once you have the bytes object, you already know what to do. In Python2, if you have a str, you have a bytes object; in Python3, use .encode with your chosen encoding.
The int("0x31", 16) part is correct:
>>> int("0x31",16)
49
But to convert that to a character, you should use the chr(...) function instead:
>>> chr(49)
'1'
Putting both of them together (on the first letter):
>>> chr(int("0x53", 16))
'S'
And processing the whole list:
>>> [chr(int(i, 16)) for i in "0x53 0x48 0x41 0x53 0x48 0x49".split()]
['S', 'H', 'A', 'S', 'H', 'I']
And finally turning it into a string:
>>> hex_string = "0x53 0x48 0x41 0x53 0x48 0x49"
>>> ''.join(chr(int(i, 16)) for i in hex_string.split())
'SHASHI'
I hope this helps!
>>> import binascii
>>> s = b'SHASHI'
>>> myWord = binascii.b2a_hex(s)
>>> myWord
b'534841534849'
>>> binascii.a2b_hex(myWord)
b'SHASHI'
>>> bytearray.fromhex("534841534849").decode()
'SHASHI'