89DEVs

Python bytes() function

The Python function bytes() returns the bytes object of the given value. While bytearray is mutable, the bytes object is immutable. We can use bytes() on lists, strings, integers, and other objects.

bytes() on list

When we use the bytes() function on a list all elements are converted into bytes code. # bytes() function on list example = [2, 5, 11] print(bytes(example)) This example returns the following bytes: b'\x02\x05\x0b'

bytes() on string

If bytes() is used on strings, it is necessary to pass the optional encoding argument in the second position. If the encoding is not passed a TypeError exception is raised. string1 = 'Python is awesome!' print(bytes(string1, 'utf-8')) This example returns the following bytes: b'Python is awesome!' It is possible to use a different encoding, for example UTF-16: string1 = 'Python is awesome!' print(bytes(string1, 'utf-16')) This returns us the following bytes: b'\xff\xfeP\x00y\x00t\x00h\x00o\x00n\x00 \x00i\x00s\x00 \x00a\x00w\x00e\x00s\x00o\x00m\x00e\x00!\x00'

bytes() on iterable list

If we use bytes() on an iterable list, it returns the bytes with binary representation of the values. list1 = [0, 1, 2, 3, 4, 5] print(bytes(list1)) In this example Python returns the following bytes: b'\x00\x01\x02\x03\x04\x05' The len() function is used to count the bytes: list1 = [0, 1, 2, 3, 4, 5] print(len(bytes(list1))) The size of bytes is returned: 6

bytes() on integers

If we use the bytes() function on an integer, it returns an array of the given size with null values. int1 = 3 print(bytes(int1)) In this example a byte of size 3 is returned: b'\x00\x00\x00'

bytes() syntax

The syntax of the bytes() function is: bytes([object], [encoding], [errors])

bytes() arguments

The bytes() function takes three optional arguments: source, to initialize the bytes encoding, to define the encoding of the string errors, to define an action when encoding fails If the first argument is a string, then the encoding argument is required. If no argument is passed, an empty byte is returned: b''

bytes() return value

The bytes() function returns bytes representation of the given arguments. If an integer is used as first argument, the integer is the size of the bytes initialized as null.

bytes() alternative

The bytes() function creates an bytes object. This object is immutable and can not be modified. If a mutable object is desired, the bytearray() function is more useful.

                
        

Summary


Click to jump to section