ZetCode

Python bytes 函数

上次修改时间:2025 年 4 月 11 日

本综合指南探讨 Python 的 bytes 函数,该函数创建一个不可变的字节序列。我们将介绍创建方法、从字符串的转换以及二进制数据处理的实际示例。

基本定义

bytes 函数返回一个不可变的 bytes 对象,表示 0 <= x < 256 范围内的字节序列。它类似于 bytearray,但不可变。

主要特点:不可变的整数序列 (0-255)、支持大多数序列操作、用于二进制数据处理和编码/解码。

创建空 Bytes

创建 bytes 对象的最简单方法是指定其长度。这将创建一个指定大小的零填充 bytes 对象。

empty_bytes.py
# Create empty bytes of length 5
empty_bytes = bytes(5)
print(empty_bytes)  # b'\x00\x00\x00\x00\x00'
print(type(empty_bytes))  # <class 'bytes'>
print(len(empty_bytes))  # 5

此示例创建一个长度为 5 的 bytes 对象,并填充空字节 (0x00)。b'' 前缀表示 Python 中的 bytes 字面量。

Bytes 对象支持标准序列操作,例如索引、切片和长度检查,如示例所示。

从整数的可迭代对象创建

您可以从整数 (0-255) 的可迭代对象创建 bytes。 这对于创建特定的字节模式很有用。

iterable_bytes.py
# Create bytes from list of integers
byte_values = bytes([65, 66, 67, 68, 69])
print(byte_values)  # b'ABCDE'

# Create bytes from range
range_bytes = bytes(range(65, 70))
print(range_bytes)  # b'ABCDE'

# Hex values
hex_bytes = bytes([0x41, 0x42, 0x43])
print(hex_bytes)  # b'ABC'

可迭代对象中的每个整数必须在 0-255 范围内。超出此范围的值将引发 ValueError

ASCII 值 65-69 对应于大写字母 A-E,因此当可打印时,bytes 对象会将它们显示为字符。

从具有编码的字符串创建

可以通过指定编码从字符串创建 Bytes 对象。 这对于文本序列化和网络通信至关重要。

string_bytes.py
# UTF-8 encoded bytes
text = "Hello, world!"
utf8_bytes = bytes(text, encoding='utf-8')
print(utf8_bytes)  # b'Hello, world!'

# Different encodings
utf16_bytes = bytes(text, encoding='utf-16')
print(utf16_bytes)  # b'\xff\xfeH\x00e\x00l\x00...'

# Using encode() method (preferred)
encoded = text.encode('ascii')
print(encoded)  # b'Hello, world!'

encoding 参数指定如何将字符转换为字节。 UTF-8 是最常见的编码,但 ASCII 或 UTF-16 等其他编码也可用。

请注意,如最后一个示例所示,通常首选 encode() 方法而不是 bytes() 进行字符串编码。

从 Bytearray 创建 Bytes

您可以从可变的 bytearray 创建不可变的 bytes。 当您需要冻结可修改的字节序列时,这很有用。

bytearray_bytes.py
# Create mutable bytearray
mutable_data = bytearray(b'Hello')
mutable_data[0] = 74  # 'J' in ASCII

# Convert to immutable bytes
immutable_bytes = bytes(mutable_data)
print(immutable_bytes)  # b'Jello'

# Attempting to modify bytes raises TypeError
try:
    immutable_bytes[0] = 72
except TypeError as e:
    print(f"Error: {e}")  # 'bytes' object does not support item assignment

此示例显示了从可变 bytearray 到不可变 bytes 的转换。 与原始 bytearray 不同,生成的 bytes 对象无法修改。

TypeError 展示了 bytes 对象的不可变性,这是与 bytearray 的关键区别。

十六进制字符串到 Bytes

此示例展示了如何将十六进制字符串转换为 bytes 对象,这是密码操作和二进制协议中的常见任务。

hex_bytes.py
# From hex string using bytes.fromhex()
hex_str = "48656c6c6f"  # "Hello" in hex
hex_bytes = bytes.fromhex(hex_str)
print(hex_bytes)  # b'Hello'

# With spaces in hex string
spaced_hex = "48 65 6c 6c 6f"
spaced_bytes = bytes.fromhex(spaced_hex)
print(spaced_bytes)  # b'Hello'

# Convert back to hex
back_to_hex = hex_bytes.hex()
print(back_to_hex)  # '48656c6c6f'

fromhex() 类方法从十六进制字符串创建 bytes。 空格将被忽略,从而更易于读取更长的十六进制字符串。

hex() 方法将 bytes 转换回十六进制字符串,从而完成往返转换。

最佳实践

资料来源

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程