What is the difference between str and bytes?
A str is a sequence of code points and carries no encoding. bytes is a sequence of 8-bit values and carries no meaning until you name one. encode goes str → bytes, decode comes back, and the rule is to do both at the edges of your program and work in str everywhere inside.
Overview
Two different things that both print nicely
"hi" and b"hi" look almost identical and are not comparable: "hi" == b"hi" is False, and in Python 3 that is deliberate. A str has no encoding — asking for the bytes of a str is meaningless until you say which bytes, which is why encode takes an argument.
Indexing differs too. s[0] on a str gives a one-character str; b[0] on bytes gives an int. That catches people constantly.
Step through it
What to watch
- One code point became two bytes — positions stop matching.
- Slicing bytes can split a character in half; slicing str cannot.
- The boundary is always I/O: files, sockets, subprocesses.
Say this out loud
"str is text, bytes is data. Encode at the way out, decode at the way in, and never let bytes travel through your logic."