You need to go via the codecs module and the hex_codec codec (or its hex alias if available*):

codecs.encode(b'\x12', 'hex_codec')

* From the documentation: "Changed in version 3.4: Restoration of the aliases for the binary transforms".

Answer from ecatmur on Stack Overflow
Top answer
1 of 3
52

No, using encode() to hexlify isn't nice.

The way you use the hex codec worked in Python 2 because you can call encode() on 8-bit strings in Python 2, ie you can encode something that is already encoded. That doesn't make sense. encode() is for encoding Unicode strings into 8-bit strings, not for encoding 8-bit strings as 8-bit strings.

In Python 3 you can't call encode() on 8-bit strings anymore, so the hex codec became pointless and was removed.

Although you theoretically could have a hex codec and use it like this:

>>> import codecs
>>> hexlify = codecs.getencoder('hex')
>>> hexlify(b'Blaah')[0]
b'426c616168'

Using binascii is easier and nicer:

>>> import binascii
>>> binascii.hexlify(b'Blaah')
b'426c616168'
2 of 3
2

this is the same answer for the above but i modified it so it works with python 3.

import binascii
from Crypto.Cipher import AES
from Crypto import Random

def encrypt(passwrd, message):
    msglist = []
    key = bytes(passwrd, "utf-8")
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CFB, iv)
    msg = iv + cipher.encrypt(bytes(message, "utf-8"))
    msg = binascii.hexlify(msg)
    for letter in str(msg):
        msglist.append(letter)
    msglist.remove("b")
    msglist.remove("'")
    msglist.remove("'")
    for letter in msglist:
        print(letter, end="")
    print("")

def decrypt(passwrd, message):
    msglist = []
    key = bytes(passwrd, "utf-8")
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CFB, iv)
    msg = cipher.decrypt(binascii.unhexlify(bytes(message, "utf-8")))[len(iv):]
    for letter in str(msg):
        msglist.append(letter)
    msglist.remove("b")
    msglist.remove("'")
    msglist.remove("'")
    for letter in msglist:
        print(letter, end="")
    print("")
Discussions

How to convert character to hexadecimal and back?
I tried to code to convert string to hexdecimal and back for controle as follows: input = 'Україна' table = [] for item in input: table.append(item.encode('utf-8').hex()) output = '' for item in table: output += chr(int(item, 16)) print(output) To my surprise the output is total different ... More on discuss.python.org
🌐 discuss.python.org
6
0
March 22, 2023
Python 3 string to hex - Stack Overflow
In Python 2 these all worked: >>> "hello".encode("hex") '68656c6c6f' >>> b"hello".encode("hex") '68656c6c6f' >>> u"hello". More on stackoverflow.com
🌐 stackoverflow.com
how to encode exotic text byte/hex pattern/sequence
Want to encode some raw text byte/hex pattern/sequences with GH,Python or C#. Goal: 8bit Grayscale images. kind of run length structure: 4 or 1 byte chunks but you have to extract chunksize inside every chunk. So does anybody have fast code to compare every first byte pair of a chunk, read ... More on discuss.python.org
🌐 discuss.python.org
0
0
June 27, 2023
Python hex string encoding - Stack Overflow
I'm trying to convert a bytearray to and from a string. Why does the following not work? The encode seems to add an extra slash. Am I using the wrong encoding? I'm using python3.6 In [19]: b'\x88'. More on stackoverflow.com
🌐 stackoverflow.com
🌐
TutorialsPoint
tutorialspoint.com › article › decoding-and-encoding-hexadecimal-digitals-using-python
Decoding and encoding hexadecimal digitals using Python
March 26, 2026 - The following example demonstrates encoding a byte string to hexadecimal and decoding it back ? import binascii # Input byte string input_data = b'tutorialspoint python' # Encoding byte string to hexadecimal digits hex_encoded = binascii.b2a_hex(input_data) print("Encoded:", hex_encoded) # Decoding hexadecimal digits back to byte string decoded_data = binascii.a2b_hex(hex_encoded) print("Decoded:", decoded_data)
🌐
Delft Stack
delftstack.com › home › howto › python › str to hex python
How to Convert String to Hex in Python | Delft Stack
February 2, 2024 - The result of the encode() method is a sequence of bytes, which can be further processed using various methods. For example, the hex() function can be applied to convert each byte into its hexadecimal representation.
🌐
Python.org
discuss.python.org › python help
How to convert character to hexadecimal and back? - Python Help - Discussions on Python.org
March 22, 2023 - I tried to code to convert string to hexdecimal and back for controle as follows: input = 'Україна' table = [] for item in input: table.append(item.encode('utf-8').hex()) output = '' for item in table: output += chr…
🌐
GitHub
github.com › wilvk › blog-hugo › blob › master › content › posts › python-hex-strings.md
blog-hugo/content/posts/python-hex-strings.md at master · wilvk/blog-hugo
October 10, 2019 - If we start again with our original string AAA-BBB and we want to convert that to it's hexadecimal representation, it turns out there are a few ways to do this. The simplest way is to call .encode() on the string, and then .hex() on the byte array.
Author: wilvk
🌐
GitHub
github.com › TooManyVars › Hex-encoding-
GitHub - TooManyVars/Hex-encoding-: A python program i've written to encode or decode hexadecimal characters.
Note that the program decodes hex numbers in "0x" format. This argparseUtility branch, in future, will be able to encode/decode from Octadecimal as well as hex
Author: TooManyVars
Find elsewhere
🌐
Medium
medium.com › @vibha7696046324 › simple-steganography-hiding-text-messages-using-python-hex-encoding-0c17b89da928
Simple Steganography: Hiding Text Messages Using Python Hex Encoding | by Udita Kumari | Medium
December 11, 2025 - In this blog, we explore a fun and practical way to hide a message using hexadecimal encoding, a foundational concept in computer science, cryptography, and networking. By the end, you'll understand how a simple Python script can transform plain text into a string of hex values and back again.
🌐
Python
docs.python.org › 3 › library › binascii.html
binascii — Convert between binary and ASCII
Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation.
🌐
Python.org
discuss.python.org › python help
how to encode exotic text byte/hex pattern/sequence - Python Help - Discussions on Python.org
June 27, 2023 - Want to encode some raw text byte/hex pattern/sequences with GH,Python or C#. Goal: 8bit Grayscale images. kind of run length structure: 4 or 1 byte chunks but you have to extract chunksize inside every chunk. So does …
🌐
Linux Hint
linuxhint.com › string-to-hexadecimal-in-python
String to Hexadecimal in Python – Linux Hint
We can also convert the normal string to a hexadecimal string that doesn’t have any hexadecimal character. For that, we have to convert the string to byte using the method encode (), and then we can convert the string to hexadecimal as shown below:
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-hex-to-string-in-python
Convert Hex to String in Python - GeeksforGeeks
July 23, 2025 - The codecs module can directly decode a hex string into bytes, which can then be converted to a string.
🌐
GitHub
github.com › topics › hex-encoding
hex-encoding · GitHub Topics · GitHub
mac unicode ssr hash md5 ss base64-encoding base64-decoding url-encoding url-decoding hex-encoding hex-decoding ... Experimental toolkit for encoding and transporting binary data across constrained or text-only communication channels (Python + VBA, Base64/Hex, PDF carrier).
🌐
Medium
medium.com › @nawazmohtashim › convert-hex-to-string-in-python-a-comprehensive-guide-36d4f128cd9e
Convert Hex to String in Python: A Comprehensive Guide | by Mohd Mohtashim Nawaz | Medium
December 13, 2023 - In this example, the hex() function is used to convert the integer 255 to a hex string, and then the '0x' prefix is removed. The binascii module in Python provides several functions for binary-to-text and text-to-binary conversions, including hex decoding.
🌐
Sling Academy
slingacademy.com › article › python-ways-to-convert-a-string-to-a-hexadecimal-value
Python: 3 ways to convert a string to a hexadecimal value - Sling Academy
May 27, 2023 - Encode the string to bytes using the desired encoding, such as encode("utf-8"). Call the binascii.hexlify() function to convert the bytes to a hexadecimal representation.