xxxxxxxxxx
byte_value = b'\xb9'
hex_string = "0x" + byte_value.hex().upper()
print(hex_string) # 0xB9
xxxxxxxxxx
Suppose your hex string is something like
>>> hex_string = "deadbeef"
Convert it to a bytearray (Python 3 and 2.7):
>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')
Convert it to a bytes object (Python 3):
>>> bytes.fromhex(hex_string)
b'\xde\xad\xbe\xef'
** Note that bytes is an immutable version of bytearray.
Convert it to a string (Python ≤ 2.7):
>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"
xxxxxxxxxx
import codecs
is_string = " "
is_bytes = is_string.encode()
is_hex = codecs.encode(is_bytes, "hex")
print(is_hex)
# b'20'