Python 3
AttributeError
String Handling
Common Errors
Decoding

AttributeError: 'str' object has no attribute 'decode' in Python 3

Codemia Knowledge Hub ·

AttributeError: 'str' object has no attribute 'decode' means you called .decode() on a string in Python 3. A Python 3 str is already Unicode text, so there is nothing to decode: .decode() exists only on bytes. Remove the .decode() call, or fix the source so it produces bytes before you decode.

The error usually shows up when porting Python 2 code, or when a library returns str where you expected bytes.

How str and bytes changed from Python 2 to Python 3

python
1# Python 2:
2#   str   = bytes (raw byte sequence)
3#   unicode = text (Unicode characters)
4#   "hello".decode('utf-8')  → u"hello" (bytes → unicode)
5
6# Python 3:
7#   str   = text (Unicode characters, like Python 2's unicode)
8#   bytes = raw byte sequence (like Python 2's str)
9#   b"hello".decode('utf-8')  → "hello" (bytes → str)
10#   "hello".decode('utf-8')   → AttributeError!

Python 3's str took the place of unicode, and bytes took the place of the old str. Since str is already text, calling .decode() on it has no meaning.

Remove .decode() when the value is already str

python
1# WRONG in Python 3
2text = "Hello, World!"
3result = text.decode('utf-8')  # AttributeError
4
5# RIGHT — text is already a str, no decoding needed
6result = text

Check the type when it could be either

If you don't know whether you will get str or bytes:

python
1def ensure_str(value, encoding='utf-8'):
2    if isinstance(value, bytes):
3        return value.decode(encoding)
4    return value  # Already a str
5
6# Works with both types
7ensure_str(b"hello")   # "hello" (decoded from bytes)
8ensure_str("hello")    # "hello" (returned as-is)

Where the error typically comes from

Reading files

python
1# Binary mode returns bytes — decode is needed
2with open('data.bin', 'rb') as f:
3    content = f.read()          # bytes
4    text = content.decode('utf-8')  # OK
5
6# Text mode returns str — decode is NOT needed
7with open('data.txt', 'r', encoding='utf-8') as f:
8    content = f.read()          # str
9    # content.decode('utf-8')   # AttributeError!

HTTP responses

python
1import urllib.request
2
3response = urllib.request.urlopen('https://example.com')
4body = response.read()          # bytes
5text = body.decode('utf-8')     # OK — bytes → str
6
7# With requests library
8import requests
9response = requests.get('https://example.com')
10text = response.text            # Already str — no .decode() needed
11# response.text.decode('utf-8') # AttributeError!
12content = response.content      # bytes — .decode() works here

Base64 encoding

python
1import base64
2
3# Encoding: str → bytes → base64 bytes
4original = "Hello, World!"
5encoded = base64.b64encode(original.encode('utf-8'))  # bytes
6print(encoded)  # b'SGVsbG8sIFdvcmxkIQ=='
7
8# Decoding: base64 bytes → bytes → str
9decoded = base64.b64decode(encoded)  # bytes
10text = decoded.decode('utf-8')       # str: "Hello, World!"
11
12# Common mistake: decoding the base64 string representation
13encoded_str = encoded.decode('ascii')  # "SGVsbG8sIFdvcmxkIQ=="
14# encoded_str.decode('utf-8')  # AttributeError — it's already str

JSON handling

python
1import json
2
3# json.loads accepts both str and bytes in Python 3.6+
4data = json.loads('{"key": "value"}')      # str input — OK
5data = json.loads(b'{"key": "value"}')     # bytes input — OK
6
7# Common mistake from Python 2 code:
8response_body = b'{"key": "value"}'
9# text = response_body.decode('utf-8')  # Not needed for json.loads
10data = json.loads(response_body)  # Works directly with bytes

Database results

python
1# Some database drivers return bytes for BLOB/BINARY columns
2row = cursor.fetchone()
3binary_field = row[0]  # bytes if BLOB column
4
5if isinstance(binary_field, bytes):
6    text = binary_field.decode('utf-8')
7else:
8    text = binary_field  # Already str (TEXT/VARCHAR column)

encode() versus decode()

python
1# str → bytes: encode
2text = "Hello"
3raw = text.encode('utf-8')      # b'Hello'
4
5# bytes → str: decode
6raw = b"Hello"
7text = raw.decode('utf-8')      # "Hello"
8
9# Memory aid:
10# encode = "en-code" = put INTO bytes (code)
11# decode = "de-code" = take OUT of bytes (back to text)
  • Leftover str.decode() calls after a Python 2 migration: either remove the call or make sure the variable holds bytes instead of str.
  • Mixing str and bytes in concatenation: "text" + b"bytes" raises TypeError in Python 3. Decode the bytes or encode the string so both operands have the same type.
  • .encode().decode() as a no-op: text.encode('utf-8').decode('utf-8') goes to bytes and straight back to str, which does nothing for valid UTF-8 text. Remove both calls.
  • Assuming all bytes are UTF-8: .decode('utf-8') on bytes that are not valid UTF-8 (for example Latin-1 data or binary files) raises UnicodeDecodeError. Use .decode('latin-1') or .decode('utf-8', errors='replace') when the encoding is unknown.
  • Libraries that changed return types: some libraries returned bytes in older versions and str in newer ones, so a .decode() on the result breaks after an upgrade. Check the changelog and use an isinstance check for compatibility.

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