Python 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:
Example 3
Use bytes() to encode the list of integers [5, 6, 7], and print the number of bytes in the list:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours