bytes#
bytes is the operator’s wire-format type. Immutable
sequence of integers in [0, 255]. Same method surface as
str for the methods that make sense at the byte level. Always
specify encoding when crossing the boundary to str.
Encode a str to bytes.
"café".encode("utf-8") # b'caf\xc3\xa9'
Decode bytes to str.
b"caf\xc3\xa9".decode("utf-8") # "café"
Build from a hex string; round-trip back to hex.
header = bytes.fromhex("4d5a9000") # MZ header start
header.hex() # '4d5a9000'
Common encodings.
Encoding |
When |
|---|---|
|
The default. Variable-width; ASCII-compatible. |
|
Strict 7-bit; raises on non-ASCII. Use for protocols that are pure ASCII (HTTP headers, SMTP). |
|
1:1 byte mapping. Useful for round-tripping arbitrary
bytes through |
|
Windows wide strings; surrogate pairs. |
bytearray#
bytearray is the mutable sibling. Same interface, with
in-place mutation via slice assignment and append / extend.
buf = bytearray(b"HTTP/1.1 ")
buf.extend(b"200 OK\r\n")
buf[0:4] = b"http" # in-place
bytes(buf) # freeze a snapshot
memoryview#
memoryview is the zero-copy slice over a bytes /
bytearray / array.array / numpy array. Read or write
without copying the backing buffer.
Build a view over a buffer; slicing produces another view, not a copy.
buf = bytearray(b"payload-bytes")
mv = memoryview(buf)
mv[0:7] # <memory at ...>
Materialise a view as bytes when the consumer wants a copy.
bytes(mv[0:7]) # b'payload'
Slice-assign through the view to mutate the backing buffer in place.
mv[8:13] = b"chunk"
Use memoryview when feeding large buffers to a syscall or a
parser that accepts the buffer protocol; the alternative
buf[a:b] copies.
Method catalog#
The complete instance-method surface on bytes. Most are
mirrors of the str methods that make sense on byte
sequences. bytearray adds the in-place mutators below.
Common#
Method |
Effect |
|---|---|
|
Decode to |
|
Hex-encoded string. |
|
Parse a hex string (classmethod). |
|
Non-overlapping occurrence count. |
|
Lowest index of |
|
Highest index or |
|
Like |
|
Like |
|
Prefix test. |
|
Suffix test. |
|
Replace occurrences. |
|
Per-byte substitution via a |
|
Build a translation table (staticmethod). |
Split, join, trim, case#
Method |
Effect |
|---|---|
|
Split on |
|
Split from the right. |
|
Split on newline sequences. |
|
Split into |
|
Split at the last |
|
Concatenate iterable with this sequence between. |
|
Trim from both ends. |
|
Trim leading. |
|
Trim trailing. |
|
Strip prefix if present (3.9+). |
|
Strip suffix if present (3.9+). |
|
Left-justify to width. |
|
Right-justify to width. |
|
Centre to width. |
|
Left-pad with |
|
Lowercase ASCII characters. |
|
Uppercase ASCII characters. |
|
Title-case ASCII words. |
|
Swap ASCII case. |
|
Capitalise the first byte. |
|
Replace tabs with spaces. |
Predicates#
Method |
|
|---|---|
|
All bytes are ASCII letters. |
|
All bytes are ASCII digits. |
|
All bytes are ASCII alphanumeric. |
|
All bytes are ASCII whitespace. |
|
Every byte is |
|
Cased bytes are lowercase. |
|
Cased bytes are uppercase. |
|
Title-cased. |
bytearray-only#
In addition to every method above, bytearray supports
in-place mutation.
Method |
Effect |
|---|---|
|
Append a single byte. |
|
Append every byte from an iterable. |
|
Insert at index. |
|
Remove and return a byte. |
|
Remove the first occurrence by value. |
|
Drop every byte. |
|
Reverse in place. |
A few method examples.
hex and bytes.fromhex round-trip a hex string.
b"\xde\xad\xbe\xef".hex()
'deadbeef'
bytes.fromhex("deadbeef")
b'\xde\xad\xbe\xef'
find returns the first index of a sub-sequence or -1.
b"the quick fox".find(b"quick")
4
replace returns a new bytes with the replacement
applied; bytes is immutable so the original is unchanged.
b"GET / HTTP/1.0".replace(b"HTTP/1.0", b"HTTP/1.1")
b'GET / HTTP/1.1'
bytearray.extend mutates the buffer in place.
buf = bytearray(b"HTTP/1.1 ")
buf.extend(b"200 OK\r\n")
bytes(buf)
b'HTTP/1.1 200 OK\r\n'
Operator overloading#
bytes and bytearray share most of the sequence-protocol
dunders.
Operator |
Dunder |
Returns |
|---|---|---|
|
|
Concatenation. |
|
|
Repetition. |
|
|
Equality. |
|
|
Lexicographic less than. |
|
|
Hash ( |
|
|
Sub-sequence test (or single-byte membership). |
|
|
Index returns an |
|
|
In-place slice assignment ( |
|
|
Length. |
|
|
Byte-by-byte iteration (yields |
|
|
|
A wire-frame class can use __bytes__ so bytes(frame)
serialises to the wire form.
class Frame:
def __init__(self, op, payload): self.op, self.payload = op, payload
def __bytes__(self):
return bytes([self.op, len(self.payload)]) + self.payload
bytes(Frame(0x10, b"hello"))
b'\x10\x05hello'
A sub-sequence test reads naturally with in; behind the
scenes Python calls __contains__.
b"deadbeef" in b"the deadbeef header"
True