What happens when a text decoder encounters bytes that are not valid UTF-8?
Quick answer
A decoder’s response depends on its error handling. In Python, the default strict handler raises a UnicodeError; replace inserts U+FFFD (�), and ignore discards malformed data. A replacement character marks a decoding problem—it does not restore or reveal the original intended character. If the bytes matter, keep the original data and inspect the decoder’s settings before choosing how to handle them. [S1]
The question, the details, the next step.
A practical checklist
Keep an untouched copy of the original bytes before experimenting.
Record the encoding, decoder, error handler, and exact error or replacement marker.
Distinguish a visible replacement character from the original intended text.
Use a diagnostic approach that preserves or exposes problematic bytes instead of silently discarding them.
Verify proposed corrections against an independent, trusted copy or source.
A few more useful answers
Does U+FFFD tell me which byte was invalid?
No. It indicates that a replacement was inserted, but it does not recover the original character or, by itself, identify the underlying bytes. Keep the original data if you need to investigate further. [S1]
Is `ignore` a safe way to fix a decoding error?
It discards malformed data, so the resulting text may omit information. Use it only when dropping that data is acceptable for your purpose, and retain the original if the bytes may matter. [S1]
Can Python’s `surrogateescape` recover what the writer intended?
No. It can preserve certain undecodable bytes for a later round trip when the same handler is used to encode them again; it does not infer the intended character. [S1]
Sources
References used for this guide.
- [S1] Python 3.15 codecs — codec error handlers docs.python.org · Checked
