What does the b prefix in front of a Python string literal do?
Codemia Knowledge Hub ·
The b prefix in front of a string literal creates a bytes object instead of a regular text string. In Python 3, b"Hello" produces a bytes value containing the ASCII-encoded representation of "Hello", while "Hello" produces a str containing Unicode text. The difference matters for network I/O, binary files, cryptographic functions and any API that works on raw bytes rather than readable characters.
How str and bytes differ
Python 3 strictly separates text from binary data. A str is a sequence of Unicode code points; a bytes is a sequence of integers from 0 to 255. They are not interchangeable.
This prevents a whole class of encoding bugs from Python 2, where str and bytes were conflated and silently converted using ASCII, which broke as soon as non-ASCII characters appeared.
What you can put in a b"" literal
A bytes literal accepts only ASCII characters and escape sequences. Non-ASCII characters cannot be typed in directly:
To get non-ASCII text as bytes, encode a str:
Converting between str and bytes
encode() goes from str to bytes and decode() from bytes to str. Both take an encoding, and UTF-8 is the standard choice.
The wrong encoding gives an exception or garbled text:
When you need bytes
Many libraries and protocols (HTTP, WebSockets, database drivers, serialization formats) also return bytes and expect bytes as input.
str vs bytes at a glance
| Feature | str | bytes |
| Prefix | None (or u"" in Python 2) | b"" |
| Contains | Unicode code points | Integers 0-255 |
| Indexing returns | A one-character string | An integer |
| Encoding | Abstract text (no specific encoding) | Raw encoded data |
| Mutable variant | None (str is immutable) | bytearray |
| Concatenation | "a" + "b" works | b"a" + b"b" works |
| Mixed concatenation | "a" + b"b" raises TypeError | Must encode/decode first |
| File mode | "r" / "w" (text mode) | "rb" / "wb" (binary mode) |
| Use case | Display, text processing | I/O, binary protocols, hashing |
Mutable bytes with bytearray
bytes is immutable like str; bytearray is mutable like list. Use bytearray to build binary data incrementally or change it in place.
The b prefix in Python 2
In Python 2 the b prefix exists but does nothing: str is already a byte string, so b"hello" is identical to "hello". The prefix was added for forward compatibility, so code could run on both Python 2 and 3.
In code that must run on both versions, b"" for binary data and u"" for text makes the intent explicit.
Mistakes to avoid with bytes
- Mixing
strandbytesin concatenation or comparison. Python 3 raisesTypeErrorinstead of converting silently, on purpose. Always encode or decode explicitly. - Calling
decode("ascii")on data with non-ASCII bytes. UTF-8 is almost always the right default unless a legacy protocol specifies otherwise. - Assuming
len(encoded)equalslen(original_string). Characters outside ASCII take more than one byte in UTF-8, so a 4-character string can be 4 to 16 bytes depending on the characters and encoding. - Forgetting binary mode (
"rb"/"wb") for non-text files. Text mode applies encoding/decoding and newline translation, which corrupts binary data. - Treating
bytesas printable text. Therepr()of a bytes object shows printable ASCII directly and escapes everything else, sob'hello'looks like a string but is not one.
Related reading
- What does the Ellipsis object do?
- What does the fit method in scikit-learn do?
- What does the .numpy function do?
- What does the slash mean when help is listing method signatures?
- What does the use_multiprocessing input argument in keras mode.fit do?
- What does the yield keyword do in Python?
- What does this error InvalidArgumentError see above for traceback Expected dimension in the range -1, 1, but got 1 mean?
- What does ValueError cannot reindex from a duplicate axis mean?
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.