# How To Solve Error “UnicodeDecodeError: ‘ASCII’ codec can’t decode byte“

Are you having trouble with the error “UnicodeDecodeError: ‘ASCII’ codec can’t decode byte“? Don’t worry! Let’s follow this article. We will give you some solutions to fix it.

## The reasonof the “UnicodeDecodeError: ‘ASCII’ codec can’t decode byte“ error

The error happens when you try to decode some string, but the “ASCII” codec does not match the codec used to encode. Let’s go into detail.

Example :

# string.txt file :
# ◎🄷ҽⓁlόw🄾rlĎ⊰⊹
# Hello, Welcome to learnshareit.com
with open('string.txt', 'r', encoding='ascii') as file:

print(sample)

Output :

The error occurs because the first line string “string.txt” does not use ‘ASCII’ encoding, so it will not match to decode. If you know exactly what your string encode‘s encoding, you can define it through encoding. If not, you should try passing in the ‘UTF-8’ encoding first because it is the most common way, and it can encode over a million character code points in Unicode.

## How to fix this error?

### Solution 1: Using UTF-8 encoding

Example :

# string.txt file :
# ◎🄷ҽⓁlόw🄾rlĎ⊰⊹
# Hello, Welcome to learnshareit.com
with open('string.txt', 'r', encoding='UTF-8') as file:

print(sample)

Output :

['◎🄷ҽⓁlόw🄾rlĎ⊰⊹\n', 'Hello, Welcome to learnshareit.com\n']

Or when you are trying to use encode() the method in Python.

Example :

symbolString = '◎🄷ҽⓁlόw🄾rlĎ⊰⊹'
encodedString = symbolString.encode()
decodedString = encodedString.decode(encoding='ascii')

print(decodedString)

It also gets an error.

Output :

Example :

symbolString = '◎🄷ҽⓁlόw🄾rlĎ⊰⊹'
encodedString = symbolString.encode()
decodedString = encodedString.decode(encoding='utf-8')

print(decodedString)

Output :

◎🄷ҽⓁlόw🄾rlĎ⊰⊹

String contains some special encoding type like UTF-8, UTF-16, ISO-8895-1, GBK, Big5, etc. But it will sometimes be too hard for you to specify exactly what encoding type your file uses. So you can use the solution below.

### Solution 2: Using errors parameter

You can try passing in ‘errors’ argument the ‘ignore’ keyword to ignore characters which get errors and can’t be decoded.

Example:

# string.txt file
# ◎🄷ҽⓁlόw🄾rlĎ⊰⊹
# Hello, Welcome to learnshareit.com
with open('string.txt', 'r', encoding='ascii', errors='ignore') as file:

print(sample)

Output:

['lwrl\n', 'Hello, Welcome to learnshareit.com\n']

## Summary

The python error “UnicodeDecodeError: ’ascii’ codec can’t decode byte in position” happens when you use ‘ASCII’ codec for some string that can not decode with ‘ASCII’ codec. To fix it, you can define the correct encoding.