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.
Code
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 firstOutput
Captured from a sandboxed run of this snippet in the build pipeline.
[72, 105, 33]
72 int
b'H' bytes
['H', 'i', '!']
False
TrueWhat 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
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.