When I first started messing around with python strings and unicode, It took me awhile to understand the jargon of decode and encode too, so here's my post from here that may help:


Think of decoding as what you do to go from a regular bytestring to unicode and encoding as what you do to get back from unicode. In other words:

You de-code a str to produce a unicode string (in Python 2)

and en-code a unicode string to produce a str (in Python 2)

So:

unicode_char = u'\xb0'

encodedchar = unicode_char.encode('utf-8')

encodedchar will contain your unicode character, displayed in the selected encoding (in this case, utf-8).

The same principle applies to Python 3. You de-code a bytes object to produce a str object. And you en-code a str object to produce a bytes object.

Answer from Aphex on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › best solution for unicodedecodeerror ?
r/learnpython on Reddit: Best solution for UnicodeDecodeError ?
July 5, 2021 -

I'm processing text that comes from the internet and the script keeps exiting with a unicode decode error.

I need this problem to 100% go away and it doesn't matter if the text is encoded properly for the sake of my project, so this problem is really frustrating.

I have verified there are indeed bad unicode characters causing the script to exit, but it's just so frustrating that python doesn't throw a warning instead of exiting as the script would run perfectly if it didn't.

If I have to use a regex to filter out all non alphanumeric/punctuation characters then I will, but I am assuming there is a better solution.

Error:

Traceback (most recent call last):

File "process.py", line 23, in <module>

read_content =file.read()

File "C:\Users\removed\Anaconda3\envs\dev1\lib\encodings\cp1252.py", line 23, in decode

return codecs.charmap_decode(input,self.errors,decoding_table)[0]

Code:

file = open(i, 'r', encoding='utf-8', errors='ignore')

read_content = file.read()

file.close()
Discussions

How to get python to tolerate UTF-8 encoding errors - Stack Overflow
I have a set of UTF-8 texts I have scraped from web pages. I am trying to extract keywords from these files like so: import os import json from rake_nltk import Rake rake_nltk_var = Rake() director... More on stackoverflow.com
🌐 stackoverflow.com
utf 8 - Decode byte to utf-8 in Python: 'errors="ignore"' not working - Stack Overflow
Question: I read the docs and put errors="ignore" in my code but it isn't working! Why? ... You have an Encode error, caused by trying to print Unicode text to a Windows console that can't handle your text. ... This is why the traceback is important; look at that too, not just the exception you get. The traceback would have shown you that the error takes place on the print(html) line, not the line with the html.decode... More on stackoverflow.com
🌐 stackoverflow.com
April 1, 2017
UnicodeDecodeError in Python when reading a file, how to ignore the error and jump to the next line? - Stack Overflow
Your file doesn't appear to use the UTF-8 encoding. It is important to use the correct codec when opening a file. You can tell open() how to treat decoding errors, with the errors keyword: More on stackoverflow.com
🌐 stackoverflow.com
Best solution for UnicodeDecodeError ?
Your code looks ok. Are you sure you pressed 'save'? Are you sure you are editing the right line? Are you sure you are running the same file you are editing? Add one of these before the error line: print('made it this far') More on reddit.com
🌐 r/learnpython
11
1
July 5, 2021
🌐
GitHub
github.com › paulscherrerinstitute › py_elog › issues › 5
.decode('utf-8') throws an error if not utf-8; suggest to add `'ignore'` ? · Issue #5 · paulscherrerinstitute/py_elog
September 26, 2018 - should .decode('utf-8') be exchanged with .decode('utf-8','ignore') ? or some optional toggle? https://docs.python.org/3/howto/unicode.html#the-string-type · py_elog/elog/logbook.py · Line 258 in b75a715 · returned_msg = resp_message.decode('utf-8').splitlines() py_elog/elog/logbook.py · Line 361 in b75a715 · if re.findall('<td.*?class="errormsg".*?>.*?</td>', resp_message.decode('utf-8'), flags=re.DOTALL): py_elog/elog/logbook.py ·
Author: paulscherrerinstitute
🌐
Python
docs.python.org › 3 › library › codecs.html
codecs — Codec registry and base classes
Changed in version 3.2: Before 3.2, the errors argument was ignored; 'replace' was always used to encode, and 'ignore' to decode. Changed in version 3.3: Support any error handler.
🌐
Johnlekberg
johnlekberg.com › blog › 2020-04-03-codec-errors.html
Handling encoding and decoding errors in Python
April 3, 2020 - The default strategy (errors="strict") raises an exception when an error occurs. But, sometimes you want your program to continue processing data, either by omitting bad data (errors="ignore") or by replacing bad data with replacement characters (errors="replace").
🌐
Google Groups
groups.google.com › g › comp.lang.python › c › UfXqjKRnIxo
using DictReader() with .decode('utf-8', 'ignore')
(python 3) > with open(dfile, 'rb') as f: > for line in f: > > line > = line.decode('utf-8', 'ignore').split(',') > > How can I ​do accomplish decode('utf-8', 'ignore') when reading with > DictReader() Which DictReader? Do you mean the one in the csv module? I will assume so. I haven't tried it, but I think something like this will work: # untested with open(dfile, 'r', encoding='utf-8', errors='ignore', newline='') as f: reader = csv.DictReader(f) for row in reader: print(row['fieldname']) -- Steven
🌐
Delft Stack
delftstack.com › home › howto › python › decode utf 8 python
How to Decode UTF-8 in Python | Delft Stack
February 12, 2024 - We then decode the same bytes with errors='ignore' and errors='replace'. With 'ignore', the invalid sequence is simply skipped, and with 'replace', it’s replaced with the Unicode replacement character �. ... In Python, handling files with ...
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 41451081 › decode-byte-to-utf-8-in-python-errors-ignore-not-working
utf 8 - Decode byte to utf-8 in Python: 'errors="ignore"' not working - Stack Overflow
April 1, 2017 - def reqURL(): request = urllib.request.urlopen('https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat') html = request.read() html = html.decode(encoding="utf-8", errors="ignore") print(html) Error: UnicodeEncodeError: 'charmap' codec can't encode character '\u017d' in position 468663: character maps to <undefined> Question: I read the docs and put errors="ignore" in my code but it isn't working! Why? python ·
🌐
Python documentation
docs.python.org › 3 › howto › unicode.html
Unicode HOWTO — Python 3.14.7 documentation
Legal values for this argument are 'strict' (raise a UnicodeDecodeError exception), 'replace' (use U+FFFD, REPLACEMENT CHARACTER), 'ignore' (just leave the character out of the Unicode result), or 'backslashreplace' (inserts a \xNN escape sequence).
🌐
Bobby Hadz
bobbyhadz.com › blog › python-remove-non-utf-8-characters-from-string
Remove the non utf-8 characters from a String in Python | bobbyhadz
Set the errors keyword argument to ignore to drop any non utf-8 characters. Use the bytes.decode() method to decode the bytes object to a string.
Top answer
1 of 1
111

Your file doesn't appear to use the UTF-8 encoding. It is important to use the correct codec when opening a file.

You can tell open() how to treat decoding errors, with the errors keyword:

errors is an optional string that specifies how encoding and decoding errors are to be handled–this cannot be used in binary mode. A variety of standard error handlers are available, though any error handling name that has been registered with codecs.register_error() is also valid. The standard names are:

  • 'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect.
  • 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss.
  • 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data.
  • 'surrogateescape' will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.
  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.
  • 'backslashreplace' (also only supported when writing) replaces unsupported characters with Python’s backslashed escape sequences.

Opening the file with anything other than 'strict' ('ignore', 'replace', etc.) will then let you read the file without exceptions being raised.

Note that decoding takes place per buffered block of data, not per textual line. If you must detect errors on a line-by-line basis, use the surrogateescape handler and test each line read for codepoints in the surrogate range:

import re

_surrogates = re.compile(r"[\uDC80-\uDCFF]")

def detect_decoding_errors_line(l, _s=_surrogates.finditer):
    """Return decoding errors in a line of text

    Works with text lines decoded with the surrogateescape
    error handler.

    Returns a list of (pos, byte) tuples

    """
    # DC80 - DCFF encode bad bytes 80-FF
    return [(m.start(), bytes([ord(m.group()) - 0xDC00]))
            for m in _s(l)]

E.g.

with open("test.csv", encoding="utf8", errors="surrogateescape") as f:
    for i, line in enumerate(f, 1):
        errors = detect_decoding_errors_line(line)
        if errors:
            print(f"Found errors on line {i}:")
            for (col, b) in errors:
                print(f" {col + 1:2d}: {b[0]:02x}")

Take into account that not all decoding errors can be recovered from gracefully. While UTF-8 is designed to be robust in the face of small errors, other multi-byte encodings such as UTF-16 and UTF-32 can't cope with dropped or extra bytes, which will then affect how accurately line separators can be located. The above approach can then result in the remainder of the file being treated as one long line. If the file is big enough, that can then in turn lead to a MemoryError exception if the 'line' is large enough.

🌐
codelessgenie
codelessgenie.com › blog › unicodedecodeerror-in-python-when-reading-a-file-how-to-ignore-the-error-and-jump-to-the-next-line
Python UnicodeDecodeError: How to Ignore Errors and Skip Lines When Reading a File with Non-ASCII Characters — CodeLessGenie.com
UnicodeDecodeError is a common hurdle when reading files with non-ASCII characters, but Python provides flexible tools to handle it: Use errors='ignore' or errors='replace' to bypass bad bytes.
🌐
GitHub
gist.github.com › miraculixx › 84ac194c77f04817eeb3
Tired of Python's UnicodeDeocodeError, ascii codec can't decode? Here's how to fix it, once and for all. · GitHub
Tired of Python's UnicodeDeocodeError, ascii codec can't decode? Here's how to fix it, once and for all. - asciidecodeerror.py
🌐
py4u
py4u.org › blog › python-script-to-convert-from-utf-8-to-ascii
Python Script to Convert UTF-8 to ASCII: Fixing UnicodeDecodeError When Using 'ignore' Parameter
If you decode UTF-8 bytes containing invalid sequences (e.g., b'\xff', an invalid UTF-8 byte) with utf-8 codec and errors='ignore', Python skips the invalid byte.
🌐
Tutorialspoint
tutorialspoint.com › python › string_decode.htm
Python String decode() Method
Str.decode(encoding='UTF-8',errors='strict') The following are the parameters of the python string decode() function. encoding − This parameter specifies the encodings to be used. For a list of all encoding schemes, please visit: Standard Encodings. errors − This parameter specifies an error handling scheme. The default for errors is 'strict' which means that the encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error().
🌐
OneUptime
oneuptime.com › home › blog › how to fix 'unicodedecodeerror' in python
How to Fix 'UnicodeDecodeError' in Python
January 23, 2026 - Python's open() and decode() support error handling modes: # 'ignore' - skip problematic bytes with open('data.txt', 'r', encoding='utf-8', errors='ignore') as f: content = f.read() # Missing characters where errors occurred # 'replace' - replace ...
🌐
Python Module of the Week
pymotw.com › 2 › codecs
codecs – String encoding and decoding - Python Module of the Week
$ python codecs_decode_error.py strict Original : u'pi: \u03c0' File contents: ff fe 70 00 69 00 3a 00 20 00 c0 03 ERROR: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte · Switching to ignore causes the decoder to skip over the invalid bytes.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Error with decode 'utf-8' - Raspberry Pi Forums
Quite possibly the string you are trying to decode is not utf-8 encoded. Oh no, not again. ghp · Posts: 4625 · Joined: Wed Jun 12, 2013 12:41 pm · Thu Nov 23, 2023 5:48 am · modify the code a bit: Code: Select all · data = ser.readline(bytesToRead) # know your data, so print to console print(data) mess += data.decode('ascii', errors='ignore') Locked · Print view · 3 posts • Page 1 of 1 · Return to “Python” ·
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-strings-decode-method
Python Strings decode() method - GeeksforGeeks
May 11, 2026 - 2. errors (Optional): Specifies how to handle errors during decoding: strict (default): Raises an error for invalid characters. ignore: Ignores errors and proceeds. replace: Replaces invalid characters with a placeholder.