bytes()

Returns a byte immutable object representing the given bytes of an object.

Syntax

bytes(source, encoding, error)

Parameters

  • source (optional): specifies the source to initialize the byte represented object.
  • encoding(optional): specifies the encoding method of the object.
  • errors (optional): specifies the action to take in case of error.

Example 1

Use bytes() to encode the string "Welcome to Codecademy!" to unicode utf-8 and print the number of bytes in the string:

print(bytes("Welcome to Codecademy!", "utf-8"))
print(len(bytes("Welcome to Codecademy!", "utf-8")))

The output would be:

b'Welcome to Codecademy!'
22

Example 2

Use bytes() to encode the integer 3, and print the number of bytes in the integer:

Code
Output
Loading...

Example 3

Use bytes() to encode the list of integers [5, 6, 7], and print the number of bytes in the list:

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Python on Codecademy