bytes() function in Python

The bytes() function in Python is the constructor to the bytes class. It constructs and returns an immutable sequence of bytes.

Built-in Functions Updated 2 Mar 2017 1 min read

Function Name

bytes

Function Signature

class bytes([source[, encoding[, errors]]])

Function Overview

  • The function bytes, is a constructor to the class bytes.

  • The bytes is a collection of bytes. Elements of bytes take values from 0 to 255.

  • bytes is just similar to bytesarray. However bytes is an immutable sequence.

Example

python
# Create a null bytes array

BYTES_LENGTH    = 8

myBytes         = bytes(BYTES_LENGTH)

#print null bytes...cant do anything else as bytes is immutable

print(myBytes)

# Create bytes from strings

sampleString = "Hello World"

bytes1       = bytes(sampleString, "utf-8")

print(bytes1)

Output

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

b'Hello World'