The Python bytes() function
bytes() is a built-in Python function that creates an immutable sequence of bytes.
A byte sequence (bytes) is the basic type in Python for handling binary data, commonly used in file I/O, network transfers, image processing, and similar scenarios. bytes is immutable and cannot be modified after creation.
Word meaning: bytes means "byte", the binary data type in Python.
Basic syntax and parameters
Syntax format
bytes(source)
bytes(source, encoding)
bytes(source, encoding, errors)
Parameter Description
- Parameter source:
- Type: integer, iterable, string
- Description: the source data used to initialize the byte sequence.
- Parameter encoding(optional):
- Type: string
- Description: the encoding of the string (such as 'utf-8').
- Parameter errors(optional):
- Type: string
- Description: how encoding errors are handled.
Function description
- Return Value: returns an immutable bytes object.
- Feature: each element of bytes is an integer from 0 to 255.
Example
Example 1: creating bytes
Example
Create bytes of a specified length
b
=
bytes
(
5
)
(
b
)
Output: b'\x00\x00\x00\x00\x00'
Create from an iterable
b
=
bytes
(
[
72
,
101
,
108
,
108
,
111
]
)
(
b
)
Output: b'Hello'
Create from a string (encoding required)
b
=
bytes
(
"Hello" (Chinese)
,
encoding
=
'utf-8'
)
(
b
)
Output: b'\xe4\xbd\xa0\xe5\xa5\xbd'
Use a literal
b
=
b
"Hello"
(
b
)
Output: b'Hello'
Expected output:
b'\x00\x00\x00\x00\x00'
b'Hello'
b'\xe4\xbd\xa0\xe5\xa5\xbd'
b'Hello'
Code analysis:
- bytes(5) creates 5 zero bytes.
- Elements of an iterable must be integers from 0 to 255.
- Converting a string requires specifying an encoding.
Example 2: bytes operations
Example
Access a byte
b
=
b
"Hello"
(
b
[
0
]
)
Output: 72
(
b
[
1
]
)
Output: 101
Slicing
(
b
[
1
:
4
]
)
b'ell'
Iteration
for
byte
in
b
"ABC"
:
(
byte
,
end
=
" "
)
(
)
Output: 65 66 67
Convert back to a string
b
=
b
"Hello"
s
=
b.
decode
(
'utf-8'
)
(
s
)
Output: Hello
bytes is immutable
b[0] = 65 # this raises TypeError
Expected output:
72
101
b'ell'
65 66 67
Hello
bytes supports indexing, slicing, iteration, and other operations, but its elements cannot be modified.
Python3 built-in function