Python bytearray() Function

Python3 内置函数Python3 Built-in Functions


bytearray()It is a built-in function in Python used to create mutable byte sequences.

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 in scenarios where binary data needs to be modified frequently.

Word Definition: bytearrayIt means "byte array" and is a mutable byte sequence.


Basic Syntax and Parameters

Syntax Format

bytearray(source)
bytearray(source, encoding)
bytearray(source, encoding, errors)

Parameter Description

  • Parameter source:
    • Type: Integer, iterable object, string
    • Description: Source data used to initialize the byte array.

Function Description

  • Return Value: Returns a mutable bytearray object.
  • Features: The byte elements within it can be modified.

Examples

Example 1: Creating bytearray

Example

# Create a bytearray of specified length
b = bytearray(5)
print(b)           # Output: bytearray(b'\x00\x00\x00\x00\x00')

# Create from an iterable object
b = bytearray([72, 101, 108, 108, 111])
print(b)           # Output: bytearray(b'Hello')

# Create from a string
b = bytearray(Hello, 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 method is similar to bytes.
  2. bytearray can be initialized in multiple ways.

Example 2: Modifying bytearray

Example

# bytearray is mutable
b = bytearray("Hello", encoding='utf-8')
print(b)          # Output: bytearray(b'Hello')

# Modify a single byte
b[0] = 74  # ASCII code of 'J'
print(b)          # Output: bytearray(b'Jello')

# Append byte
b.append(33)  # 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 a rich set of modification operations: index assignment, append, extend, del, etc.


Python3 内置函数Python3 Built-in Functions


Other Extensions