hex() method of bytes class in Python

The hex() instance method of bytes class returns a string of hexadecimal digits for a bytes literal. In Python, bytes literals contain ASCII encoded bytes. Similar to a tuple, a bytes object is an immutable sequence.

Bytes Updated 20 Sep 2019 1 min read

Overview

  • The hex() instance method of bytes class, converts a bytes object into a string of hexadecimal digits.
  • The string returned by hex() method will have two hexadecimal digits for each byte from the bytes object.

Note: An escape character \x inside a byte literal means the ASCII character is encoded as hexadecimal digits.

Example

python
# Example python program using hex() to convert a bytes literal

# of ascii characters to a string literal of hexadecimal digits

bytesLiteral = b"hell\x6f";

hexVal       = bytesLiteral.hex();

print("Bytes literal of ascii characters:");

print(bytesLiteral);

print("String literal of hexadecimal digits:");

print(hexVal);

bytesLiteral = b"\x77\x6f\x72\x6c\x64";

hexVal       = bytesLiteral.hex();

print("Bytes literal of ascii characters:");

print(bytesLiteral);

print("Bytes literal of hexadecimal digits converted into a string literal:");

print(hexVal);

Output

Output
Bytes literal of ascii characters:

b'hello'

String literal of hexadecimal digits:

68656c6c6f

Bytes literal of ascii characters:

b'world'

Bytes literal of hexadecimal digits converted into a string literal:

776f726c64