Python bytes() With Examples

Python bytes() is a built-in function. This function returns bytes object that is an immutable sequence of integers in the range 0 <= x < 256.

Python bytes()

Python bytes() function syntax is:

class bytes(]])

source is used to initialize the bytes object. This is an optional argument.

encoding is optional unless source is string. It’s used to convert the string to bytes using str.encode() function.

errors is optional parameter. It’s used if the source is string and encoding fails due to some error.

There are some specific rules followed by bytes() function depending on the type of source.

  • If no argument is passed, empty bytes object is returned.
  • If source is integer, it initializes the bytes object with array of given length with null values.
  • If source is string, encoding is mandatory and it’s used to convert string to byte array.
  • If source is iterable, such as list, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Overall bytes() function is very similar to bytearray() function.

Let’s look at some of the examples of bytes() function.

bytes() with no arguments

b = bytes()

Output: b''

bytes() with string and immutability

# string to bytes
# encoding is mandatory, otherwise "TypeError: string argument without an encoding"
b = bytes('abc', 'UTF-8')
# Below code will throw error:
# TypeError: 'bytes' object does not support item assignment
# b[1] = 65  # immutable

Output: b'abc'

Note that if we try to change the element value in the bytes object, we will get an error message as shown in the above comment.

bytes() with int argument

# bytes of given size, elements initialized to null
b = bytes(5)

Output: b'x00x00x00x00x00'

bytes() with iterable

# bytes from iterable
b = bytes([1, 2, 3])

Output: b'x01x02x03'

That’s all for a quick guide of python bytes() function.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: