← 中文资源

简体中文版本

迭代 bytes 得到的是整数

迭代 bytes 得到整数,迭代 str 得到单字符字符串;b"quit" 与 "quit" 直接比较永远不相等,先 decode 再比较才是正确姿势。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

[72, 105, 33]
72 int
b'H' bytes
['H', 'i', '!']
False
True

实现要点

迭代 b“Hi!” 得到整数——推导式打印 [72, 105, 33],payload[0] 是 int。切片行为不同:payload[:1] 返回长度 1 的 bytes 对象,打印 b’H’、类型 bytes。

str 反方向迭代,产出单字符字符串。经典缺陷收尾:line == “quit” 为 False(bytes 与 str 永不相等),line.decode() == “quit” 打印 True——decode 是桥梁。

细节提醒

  • bytes 下标给 int;bytes 切片给 bytes。
  • 先 decode 再比较,或者 bytes 对 bytes 比较。

核心语句

print(line == "quit")
print(line.decode() == "quit")

代码示例

payload = b"Hi!"

# Iterating bytes yields integers, not one-character bytes objects
print([ch for ch in payload])                  # [72, 105, 33]
print(payload[0], type(payload[0]).__name__)   # 72 int

# Slicing still returns bytes, so bytes(s)[0] and bytes(s)[:1] differ
print(payload[:1], type(payload[:1]).__name__) # b'H' bytes

# str iterates the other way: one length-1 str per code point
text = "Hi!"
print([ch for ch in text])                     # ['H', 'i', '!']

# The classic bug: comparing bytes with str never matches
line = b"quit"
print(line == "quit")                          # False - different types entirely
print(line.decode() == "quit")                 # True - decode first