Iterating Bytes Yields Ints Not Chars

Iterating bytes yields integers while iterating str yields one-character strings, so comparing bytes against str silently fails until you decode.

PythonData Integrity

Code

pythonsnippet
17 lines
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

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

What the demo iterates

Iterating b“Hi!” yields integers: the comprehension prints [72, 105, 33] and payload[0] is an int. Slicing behaves differently; payload[:1] returns a length-1 bytes object, printed as b’H’ with type bytes.

str iterates the other way, yielding one-character strings. The classic bug closes the demo: line == “quit” is False because bytes and str never compare equal, and line.decode() == “quit” prints True; decoding is the bridge.

Caveats and details

  • bytes indexing gives ints; bytes slicing gives bytes.
  • Compare after decode, or compare bytes to bytes.

Interactive Tools for This Topic

FAQ

Why does comparing bytes to str fail?
They are different types with no implicit conversion; b"quit" == "quit" is False, and only payload.decode() produces a str the comparison can match.