close

[Solved] UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xd1 in position 2: ordinal not in range(128)

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xd1 in position 2: ordinal not in range(128) in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xd1 in position 2: ordinal not in range(128) Error Occurs?

Today I get the following error UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xd1 in position 2: ordinal not in range(128) in python.

How To Solve UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xd1 in position 2: ordinal not in range(128) Error ?

  1. How To Solve UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128) Error ?

    To Solve UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128) Error Unicode is not equal to UTF-8. The latter is just an encoding for the former.

  2. UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)

    To Solve UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128) Error Unicode is not equal to UTF-8. The latter is just an encoding for the former.

Solution 1

for Python 3 users. you can do

with open(csv_name_here, 'r', encoding="utf-8") as f:
    #some codes

it works with flask too 🙂

Solution 2

Unicode is not equal to UTF-8. The latter is just an encoding for the former.

You are doing it the wrong way around. You are reading UTF-8-encoded data, so you have to decode the UTF-8-encoded String into a unicode string.

So just replace .encode with .decode, and it should work (if your .csv is UTF-8-encoded).

Nothing to be ashamed of, though. I bet 3 in 5 programmers had trouble at first understanding this, if not more 😉

Update: If your input data is not UTF-8 encoded, then you have to .decode() with the appropriate encoding, of course. If nothing is given, python assumes ASCII, which obviously fails on non-ASCII-characters.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read