Python bytes()

Python bytes() function creates an immutable (unchangeable) sequence of bytes. Think of it as a read-only version of a bytearray, storing raw binary data or text encoded in a specific way. It’s useful when you need to work with data at a low level or ensure data integrity by preventing accidental modifications.

bytes() Syntax

my_bytes = bytes(source, encoding, errors)
  • my_bytes: A variable where the new bytes object will be stored.
  • bytes(): The built-in Python function you use to make a bytes object.
  • source (optional): The initial data for the bytes object. This can be a string, an integer specifying the size, or an iterable of integers.
  • encoding (optional): If the source is a string, this specifies how to encode it into bytes.
  • errors (optional): If the source is a string and there’s a problem converting it, this tells Python what to do.

Example 1: Python bytes()

my_bytes = bytes(b'hello')  
print(my_bytes)

Code Explanation

  • Line 1: Creates a bytes object directly from a bytes literal b'hello'.
  • Line 2: Prints the bytes object, showing its content.

Output

b’hello’


Example 2: Covert String to Bytes with Python bytes()

text = "Hello, world!"
my_bytes = bytes(text, 'utf-8')
print(my_bytes)

Code Explanation

  • Line 1: Assigns a string to the variable text.
  • Line 2: Creates a bytes object from the string, encoding it using UTF-8.
  • Line 3: Prints the bytes object, which now contains the byte representation of the string.

Output

b’Hello, world!’


Example 3: Covert Integer to Bytes with Python bytes()

size = 10
my_bytes = bytes(size)
print(my_bytes)

Code Explanation

  • Line 1: Assigns the desired size (10) to the variable size.
  • Line 2: Creates a bytes object with the specified size, all elements initialized to 0.
  • Line 3: Prints the bytes object.

Output

b’\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00′


Example 4: Covert Iterable (List) to Bytes with Python bytes()

my_list = [72, 101, 108, 108, 111]  # ASCII codes for "Hello"
my_bytes = bytes(my_list)
print(my_bytes)

Code Explanation

  • Line 1: Creates a list containing the ASCII codes for the characters in “Hello”.
  • Line 2: Creates a bytes object from the list of integers.
  • Line 3: Prints the bytes object, which decodes back to the original string “Hello”.

Output

b’Hello’


Example 5: Convert Iterable (List) to Bytes with Python bytes()

my_list = [11, 12, 13, 14, 15]
my_bytes = bytes(my_list)
print(my_bytes)

Code Explanation

  • Line 1: Creates a list of integers.
  • Line 2: Creates a bytes object from the list of integers.
  • Line 3: Prints the bytes object, showing the hexadecimal representation of each byte.

Output

b’\x0b\x0c\r\x0e\x0f’


Also Read

Python callable()

Python chr()