The hex codec has been chucked in 3.x. Use binascii instead:
>>> binascii.hexlify(b'hello')
b'68656c6c6f'
Answer from Ignacio Vazquez-Abrams on Stack OverflowThe hex codec has been chucked in 3.x. Use binascii instead:
>>> binascii.hexlify(b'hello')
b'68656c6c6f'
In Python 3.5+, encode the string to bytes and use the hex() method, returning a string.
s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'
Optionally convert the string back to bytes:
b = bytes(s, "utf-8")
b
# b'68656c6c6f'
Converting a string to Hex in Python 3 - Stack Overflow
String to HEX
Converting string to hex in Python 3.5
python - How to convert an int to a hex string? - Stack Overflow
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)
I am wanting to take a normal string, "My water bottle is blue" for example, and converting that into the HEX representation of how it would be stored in a txt file. I've tried .encode, binascii.hexlify, and a few other things. Any help would be appreciated.
You are looking for the chr function.
You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.
>>> chr(0x65) == '\x65'
True
>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True
Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.
This will convert an integer to a 2 digit hex string with the 0x prefix:
strHex = "0x%0.2X" % integerVariable
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