Python bytes()

Filed Under: Python

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[, encoding[, errors]]])

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()
print(b)

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')
print(b)

# 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)
print(b)

Output: b'\x00\x00\x00\x00\x00'

bytes() with iterable


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

Output: b'\x01\x02\x03'

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

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages