Python bytearray() Function
bytearray() is a built-in Python function that creates a mutable sequence of bytes.
bytearray is very similar to bytes, but with one key difference: bytearray is mutable and its bytes can be modified at any time. This makes it very useful when binary data must be modified frequently.
Word meaning: bytearray means "byte array", a mutable sequence of bytes.
Basic syntax and parameters
Syntax format
bytearray(source)
bytearray(source, encoding)
bytearray(source, encoding, errors)
Parameter Description
- Parameter source:
- Type: integer, iterable, string
- Description: the source data used to initialize the byte array.
Function description
- Return Value: returns a mutable bytearray object.
- Feature: its byte elements can be modified.
Example
Example 1: creating a bytearray
Example
Create a bytearray of a specified length
b
=
bytearray
(
5
)
(
b
)
Output: bytearray(b'\x00\x00\x00\x00\x00')
Create from an iterable
b
=
bytearray
(
[
72
,
101
,
108
,
108
,
111
]
)
(
b
)
Output: bytearray(b'Hello')
Create from a string
b
=
bytearray
(
"Hello" (Chinese)
,
encoding
=
'utf-8'
)
(
b
)
Output: bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd')
Empty bytearray
b
=
bytearray
(
)
(
b
)
Output: bytearray(b'')
Expected output:
bytearray(b'\x00\x00\x00\x00\x00')
bytearray(b'Hello')
bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd')
bytearray(b'')
Code analysis:
- The creation methods are similar to those of bytes.
- A bytearray can be initialized in several ways.
Example 2: modifying a bytearray
Example
A bytearray is mutable
b
=
bytearray
(
"Hello"
,
encoding
=
'utf-8'
)
(
b
)
Output: bytearray(b'Hello')
Modify a single byte
b
[
0
]
=
74
The ASCII code of 'J'
(
b
)
Output: bytearray(b'Jello')
Append a byte
b.
append
(
33
)
The ASCII code of '!'
(
b
)
Output: bytearray(b'Jello!')
Extend
b.
extend
(
[
33
,
33
]
)
(
b
)
Output: bytearray(b'Jello!!!')
Delete
del
b
[
0
]
(
b
)
Output: bytearray(b'ello!!!')
Expected output:
bytearray(b'Hello')
bytearray(b'Jello')
bytearray(b'Jello!')
bytearray(b'Jello!!!')
bytearray(b'ello!!!')
bytearray supports rich modification operations: index assignment, append, extend, del, and so on.
Python3 built-in function