Featurecore
bytes and bytearray
Also called bytes, bytearray, binary data, byte string, bytes.hex, bytes.fromhex, mutable bytes, b prefix.
bytes is an immutable sequence of integers from 0 to 255, and bytearray is the mutable form. An index gives an int, not a character. bytes and str do not mix: code must encode or decode.
- Language
- Python
Synopsis
data = b"Hi!\x00\xff"
print(len(data), data[0], data[0:1], list(data))
buf = bytearray(data)
buf[0] = ord("h")
buf += b"\x10"
print(buf)
print(bytes.fromhex("48 69 21"), data.hex(" "))
5 72 b'H' [72, 105, 33, 0, 255]
bytearray(b'hi!\x00\xff\x10')
b'Hi!' 48 69 21 00 ff
A bytes literal has the b prefix. An index gives an int, and a slice gives bytes. A bytearray can change in place.
Semantics
r1. "Bytes objects are immutable sequences of single bytes."1 "Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence."1
r2. "bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256 (attempts to violate this restriction will trigger ValueError)."1 Example: range.
r3. "for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)"1
r4. Besides literals, there are other ways to make bytes: "A zero-filled bytes object of a specified length: bytes(10)", "From an iterable of integers: bytes(range(20))" and "Copying existing binary data via the buffer protocol: bytes(obj)".1 Example: zero-fill.
r5. "bytearray objects are a mutable counterpart to bytes objects."2 "There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor".2 They support the mutable sequence operations.2 Example: mutate.
r6. fromhex() reads two hexadecimal digits for each byte, "with ASCII whitespace being ignored."1 hex() returns "a string object containing two hexadecimal digits for each byte in the instance", with an optional separator.1
r7. "The methods on bytes and bytearray objects don’t accept strings as their arguments, just as the methods on strings don’t accept bytes as their arguments."3 Example: mix.
r8. "Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation".4 With an encoding, "str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors)."4 Example: str-of-bytes.
r9. Bytes objects have their own % operator: "Given format % values (where format is a bytes object), % conversion specifications in format are replaced with zero or more elements of values."3 Example: percent.
Examples
buf = bytearray(b"hello world")
buf[0:5] = b"HELLO"
buf.extend(b"!!")
del buf[5]
print(buf, len(buf))
print(bytes(buf).upper(), buf.replace(b"!", b"?"))
bytearray(b'HELLOworld!!') 12
b'HELLOWORLD!!' bytearray(b'HELLOworld??')
A slice assignment, extend() and del change the bytearray in place (rule r5). replace() returns a new object.
print(b"%s: %d bytes, %x" % (b"header", 16, 255))
b'header: 16 bytes, ff'
The format and the result are bytes (rule r9).
data = "café".encode("utf-8")
print(data, len(data))
print(str(data))
print(str(data, "utf-8"), data.decode("utf-8"))
b'caf\xc3\xa9' 5
b'caf\xc3\xa9'
café café
Without an encoding, str() gives the representation of the bytes, not the text (rule r8).
Pitfalls
bytes(10) does not give the byte 10:
This code runs but gives a wrong answer on purpose.
print(bytes(10))
print(bytes([10]))
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\n'
An int argument gives that number of zero bytes. Put the value in a list to get one byte (rule r4).
A value outside 0 to 255 is an error:
This code raises ValueError, on purpose.
bytes([256])
A str argument to a bytes method is an error:
This code raises TypeError, on purpose.
b"abc".replace("a", "f")
Write b"abc".replace(b"a", b"f"), or decode the bytes to a str first (rule r7).
A loop over bytes gives ints, not characters (rule r3):
for item in b"Hi":
print(item, chr(item))
72 H
105 i
Comparison
In Go, a string is already a sequence of bytes, and []byte is the mutable form. "Converting a value of a string type to a slice of bytes type yields a non-nil slice whose successive elements are the bytes of the string."5 "Converting a slice of bytes to a string type yields a string whose successive bytes are the elements of the slice."5 So Go []byte(s) is close to Python bytearray(s.encode()). A Python str holds code points, not bytes, so the conversion in Python always needs an encoding (rule r8).
References
- Built-in Types, Python 3.15 documentation, Bytes Objects
- Built-in Types, Python 3.15 documentation, Bytearray Objects
- Built-in Types, Python 3.15 documentation, Bytes and Bytearray Operations; printf-style Bytes Formatting
- Built-in Types, Python 3.15 documentation, Text Sequence Type, str (class str)
- The Go Programming Language Specification, Conversions to and from a string type
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag K6NJVP Edit this page History Report an error Markdown