w3resource

Python: bytes() function

bytes() function

The bytes() function is used to get a new 'bytes' object.

Note: bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.

Accordingly, constructor arguments are interpreted as for bytearray()

Syntax:

bytes([source[, encoding[, errors]]])
Python: Built-in function - bytes function()

Version:

(Python 3.2.5)

Return value:

Return a new 'bytes' object, which is an immutable sequence of integers in the range 0 <= x < 256.

Example: Convert iterable list to bytes

num = [0, 200, 50, 25, 10, 255]

a = bytes(num)
print(a)

Output:

b'\x01\x02\x03\x04\x05'

Pictorial Presentation:

Python: Built-in-function - bytes() function

Example: Create a byte of given integer size

s = 10

a = bytes(s)
print(a)

Output:

b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

Example: Convert string to bytes

str = "Python bytes example."

# string with encoding 'utf-8'
a = bytes(str, 'utf-8')
print(a)

Output:

b'Python bytes example.'

Pictorial Presentation:

Python: Built-in-function - bytes() function

Python Code Editor:

Previous: bytearray()
Next: callable()

Test your Python skills with w3resource's quiz



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python/built-in-function/bytes.php