bytes()

Published Jun 19, 2021Updated Sep 3, 2021
Contribute to Docs

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:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

Example 3

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

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy