Python .hexlify()

MamtaWardhani's avatar
Published Oct 29, 2025
Contribute to Docs

The .hexlify() method from Python’s binascii module encodes binary data into a hexadecimal (base-16) ASCII representation. It’s an alias for binascii.b2a_hex() and is commonly used to represent binary data in a readable hex format. Each byte of input data is converted into a two-digit hexadecimal value.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

binascii.hexlify(data[, sep[, bytes_per_sep]])

Parameters:

  • data (bytes-like): The binary data to encode.
  • sep (optional, single character str or bytes): A separator to insert between hex groups.
  • bytes_per_sep (optional int): After every bytes_per_sep input bytes, insert sep. A negative value will count from the right end.

Return value:

Returns a bytes object containing the hexadecimal ASCII representation of the input.

Note: The returned object is always twice as long as the original data. If sep is provided, it’s inserted at the specified intervals for better readability.

Example: Converting Binary Data to Hexadecimal

This example encodes a byte string into its hexadecimal equivalent:

import binascii
message = b'Python3'
hex_value = binascii.hexlify(message)
print(hex_value)

The output of this code is:

b'507974686f6e33'

This converts each byte of 'Python3' into a two-character hexadecimal value, producing a readable byte representation.

Codebyte Example: Converting to Hexadecimal and Decoding to String

This codebyte demonstrates converting binary data into its hexadecimal representation using .hexlify():

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours