Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python bytearray() Function

Python bytearray() Function

Python3 Built-in Functions Python3 built-in 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

- Type: integer, iterable, string - Description: the source data used to initialize the byte array.

Function description


Example

Example 1: creating a bytearray

Example

Create a bytearray of a specified length

b

=

bytearray

(

5

)

print

(

b

)

         

Output: bytearray(b'\x00\x00\x00\x00\x00')

Create from an iterable

b

=

bytearray

(

[

72

,

101

,

108

,

108

,

111

]

)

print

(

b

)

         

Output: bytearray(b'Hello')

Create from a string

b

=

bytearray

(

"Hello" (Chinese)

,

encoding

=

'utf-8'

)

print

(

b

)

         

Output: bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd')

Empty bytearray

b

=

bytearray

(

)

print

(

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:

  1. The creation methods are similar to those of bytes.
  2. A bytearray can be initialized in several ways.

Example 2: modifying a bytearray

Example

A bytearray is mutable

b

=

bytearray

(

"Hello"

,

encoding

=

'utf-8'

)

print

(

b

)

         

Output: bytearray(b'Hello')

Modify a single byte

b

[

0

]

=

74

 

The ASCII code of 'J'

print

(

b

)

         

Output: bytearray(b'Jello')

Append a byte

b.

append

(

33

)

 

The ASCII code of '!'

print

(

b

)

         

Output: bytearray(b'Jello!')

Extend

b.

extend

(

[

33

,

33

]

)

print

(

b

)

         

Output: bytearray(b'Jello!!!')

Delete

del

b

[

0

]

print

(

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 Functions Python3 built-in function