bytearray()
Anonymous contributor
Published Jun 19, 2021Updated Sep 3, 2021
Contribute to Docs
Returns an array of the given bytes of an object.
Syntax
bytearray(source, encoding, error)
Parameters
source
(optional): specifies the source to initialize the bytearray.encoding
(optional): specifies the encoding method of the object.errors
(optional): specifies the action to take in case of error.
Example 1
Use bytearray()
to encode the string "Welcome to Codecademy!"
to unicode utf-8
and utf-32
, and print the length of each bytearray. Note that a source
and encoding
parameter must be provided for encoding string
data:
array_1 = bytearray("Welcome to Codecademy!", "utf-8")array_2 = bytearray("Welcome to Codecademy!", "utf-32")print(array_1)print(len(array_1))print(array_2)print(len(array_2))
The output would be:
bytearray(b'Welcome to Codecademy!')
22
bytearray(b'\xff\xfe\x00\x00W\x00\x00\x00e\x00\x00\x00l\x00\x00\x00c\x00\x00\x00o\x00\x00\x00m\x00\x00\x00e\x00\x00\x00 \x00\x00\x00t\x00\x00\x00o\x00\x00\x00 \x00\x00\x00C\x00\x00\x00o\x00\x00\x00d\x00\x00\x00e\x00\x00\x00c\x00\x00\x00a\x00\x00\x00d\x00\x00\x00e\x00\x00\x00m\x00\x00\x00y\x00\x00\x00!\x00\x00\x00')
92
Example 2
Use bytearray()
to encode the integer 5
, and print the length of the bytearray:
Example 3
Use bytearray()
to encode the list of integers [5, 6, 7]
, and print the length of the bytearray:
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
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours