bytearray Edits Binary Buffers In Place

bytearray is the mutable twin of bytes: slices reassign fixed-width fields, single bytes read as integers, and str conversion always names an encoding.

PythonData Integrity

Code

pythonsnippet
23 lines
# bytearray 可变,bytes 不可变:二进制缓冲区就地编辑用 bytearray
buffer = bytearray(b"GET / HTTP/1.1")
print("as bytes     :", bytes(buffer))

# 就地替换一段:长度可以不同
buffer[4:5] = b"/api"
print("spliced      :", bytes(buffer))

# append / extend 追加,del 切片删除;CRLF 用字节值构造,不必转义
crlf = bytes([13, 10])
buffer.extend(crlf + b"host: demo")
print("extended     :", bytes(buffer))
del buffer[-12:]
print("tail removed :", bytes(buffer))

# 单个字节按整数读写,切片仍是 bytearray
print("first byte   :", buffer[0], "= 'G'")
buffer[0:3] = b"PUT"
print("method swap  :", bytes(buffer))

# 与 str 互转必须显式给编码
text = buffer.decode("ascii")
print("decoded      :", text.lower(), "| roundtrip:", bytearray(text.encode("ascii")) == buffer)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

as bytes     : b'GET / HTTP/1.1'
spliced      : b'GET /api HTTP/1.1'
extended     : b'GET /api HTTP/1.1\r\nhost: demo'
tail removed : b'GET /api HTTP/1.1'
first byte   : 71 = 'G'
method swap  : b'PUT /api HTTP/1.1'
decoded      : put /api http/1.1 | roundtrip: True

How it works

Everything operates on top-level bindings: buffer, crlf, text.

Watch out for

  • Runs on the standard library alone; nothing to install.

Using it

The demo output is labeled (as bytes :, spliced :, extended :), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. Its state lives in module-level bindings: `buffer`, `crlf`, `text`.