How to fix SyntaxError: Non-ASCII character '\xe2'

One error that you might encounter when running Python code is:

SyntaxError: Non-ASCII character '\xe2'

This error occurs whenever you have an en dash symbol in your code in Python 2.

Python 2 uses ASCII encoding by default, so the en dash symbol which is encoded in 3 bytes as \xe2\x80\x93 in UTF-8 is not available.

Suppose you have an en dash in a string as follows:

my_str = "One–liner string"  # ❌

print my_str

Then Python 2 will raise this error:

  File "main.py", line 1
SyntaxError: Non-ASCII character '\xe2' in file main.py on line 1, 
but no encoding declared; 
see http://python.org/dev/peps/pep-0263/ for details

If you follow the given link in the error message, you’ll see that you can resolve this error by adding the source code encoding.

Add the encoding comment line at the beginning of your file as shown below:

# -*- coding: utf8 -*-

my_str = "One–liner string"

print my_str

Now you should be able to run the code without facing the error.

The en dash symbol might get into your code when you copy and paste code from the Internet. If you can’t find the character in your code, then you can use Python to scan your source code file.

Create a new .py file and write the following code:

with open("main.py") as fp:
    for i, line in enumerate(fp):
        if "\xe2" in line:
            print i, repr(line)

Replace main.py with the name of the file that’s causing the error.

You should see a response similar to this:

2 'my_str = "One\xe2\x80\x93liner string"\n'

Alternatively, you can upgrade to Python 3 which uses the UTF-8 encoding by default.

I hope this tutorial is helpful. Happy coding! 🙌

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.