Interview Q&A / Python

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What is the difference between str and bytes in Python 3?

SHORT ANSWER

str holds Unicode text, a sequence of characters. bytes holds raw 8-bit values. You encode a str to get bytes and decode bytes to get a str, and you must name the encoding, usually UTF-8.

Explain it simply

A str is the meaning of a message. bytes is the actual ink on the paper, one specific way of writing it down. The same word can be written down differently depending on the encoding, so converting between the two always needs an agreed encoding.

Files, sockets and network calls deal in bytes. Your code should work with str and convert at the edges.

Example

python
name = "रोहित"
data = name.encode("utf-8")
print(len(name))              # Output: 5
print(len(data))              # Output: 15
print(data[:3])               # Output: b'\xe0\xa4\xb0'
print(data.decode("utf-8"))   # Output: रोहित
print(b"abc"[0])              # Output: 97

Each Devanagari character here takes 3 bytes in UTF-8, so 5 characters become 15 bytes. Indexing a bytes object gives an integer, not a one-character string.

What to say in the interview

"str is a sequence of Unicode code points; bytes is a sequence of integers from 0 to 255. I convert with encode() and decode() and always pass the encoding, normally UTF-8. Mixing the two, like 'a' + b'b', raises TypeError. I decode bytes as soon as I read them and encode only when writing out."

Common mistakes

  • Assuming len(text) equals the number of bytes on disk. It does not for non-ASCII text.

#python#strings#data-types

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.