Programming
Python
String Literals
Byte Objects
Code Syntax

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.

python
1text = "Hello"
2binary = b"Hello"
3
4print(type(text))      # <class 'str'>
5print(type(binary))    # <class 'bytes'>
6
7print(text[0])         # 'H'  (a character)
8print(binary[0])       # 72   (an integer, the ASCII value of 'H')

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:

python
1# Valid
2data = b"Hello\x00\xff\n"
3
4# Invalid: SyntaxError
5# data = b"cafe"  # fine because all ASCII
6# data = b"caf\xc3\xa9"  # fine (raw bytes for UTF-8 encoded 'é')
7# data = b"café"  # SyntaxError if you paste the actual 'é' character

To get non-ASCII text as bytes, encode a str:

python
1text = "café"
2encoded = text.encode("utf-8")
3print(encoded)    # b'caf\xc3\xa9'
4print(len(text))     # 4 characters
5print(len(encoded))  # 5 bytes (the 'é' takes 2 bytes in UTF-8)

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.

python
1# str -> bytes
2message = "Hello, world"
3as_bytes = message.encode("utf-8")
4print(as_bytes)          # b'Hello, world'
5
6# bytes -> str
7raw = b"Hello, world"
8as_text = raw.decode("utf-8")
9print(as_text)           # Hello, world

The wrong encoding gives an exception or garbled text:

python
data = "café".encode("utf-8")   # b'caf\xc3\xa9'
wrong = data.decode("ascii")       # UnicodeDecodeError
wrong = data.decode("latin-1")     # "café" (wrong, but no error)

When you need bytes

python
1# Network sockets
2import socket
3s = socket.socket()
4s.connect(("example.com", 80))
5s.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
6response = s.recv(4096)  # returns bytes
7
8# Writing binary files
9with open("output.bin", "wb") as f:
10    f.write(b"\x89PNG\r\n\x1a\n")  # PNG file header
11
12# Cryptographic hashing
13import hashlib
14digest = hashlib.sha256(b"password").hexdigest()
15
16# Base64 encoding
17import base64
18encoded = base64.b64encode(b"binary data")

Many libraries and protocols (HTTP, WebSockets, database drivers, serialization formats) also return bytes and expect bytes as input.

str vs bytes at a glance

Featurestrbytes
PrefixNone (or u"" in Python 2)b""
ContainsUnicode code pointsIntegers 0-255
Indexing returnsA one-character stringAn integer
EncodingAbstract text (no specific encoding)Raw encoded data
Mutable variantNone (str is immutable)bytearray
Concatenation"a" + "b" worksb"a" + b"b" works
Mixed concatenation"a" + b"b" raises TypeErrorMust encode/decode first
File mode"r" / "w" (text mode)"rb" / "wb" (binary mode)
Use caseDisplay, text processingI/O, binary protocols, hashing

Mutable bytes with bytearray

python
1data = bytearray(b"Hello")
2data[0] = 74  # ASCII for 'J'
3print(data)   # bytearray(b'Jello')
4
5# bytearray supports in-place modification
6data.append(33)
7print(data)   # bytearray(b'Jello!')

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.

python
1# Python 2
2type(b"hello")   # <type 'str'> (bytes and str are the same)
3type(u"hello")   # <type 'unicode'>
4
5# Python 3
6type(b"hello")   # <class 'bytes'>
7type("hello")    # <class 'str'> (str is Unicode)

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 str and bytes in concatenation or comparison. Python 3 raises TypeError instead 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) equals len(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 bytes as printable text. The repr() of a bytes object shows printable ASCII directly and escapes everything else, so b'hello' looks like a string but is not one.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Data 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.

Practice algorithms