How do I correct the error "Non-ASCII character '\ xe2' in file ... but no encoding declared"?

0

I am using Python 2.7 to run a program that is in Python 3.6. I added it to the interpreters but I still see this error:

  

File "/ Users / a / Desktop / project porgramacion 2 / proyecto.py", line 17   SyntaxError: Non-ASCII character '\ xe2' in file / Users / a / Desktop / project programming 2 / project.py on line 17, but no encoding declared; see link for details

    
asked by Drax-i 19.06.2018 в 04:43
source

1 answer

2

Your module (the .py file) does not use ASCII as coding but UTF-8 (given that another encoding is not defined and I assume it works in Python 3) and it contains non-ASCII characters.

The interpreter in Python 3 uses UTF-8 as the default encoding for the source code, while Python 2 uses ASCII by default. When the Python 2 interpreter encounters a non-ASCII character, it does not know how to interpret it because it does not have the encoding information to use and throws the exception that you show:

  

Syntax error: No-ASCII character '\ xe2' in file / Users / a / Desktop / project programming 2 / project.py on line 17, but undeclared encoding;

Just as the error itself informs you, you must declare the encoding on the first or second line of the file as specified in PEP 263 - Defining Python Source Code Encodings :

# -*- coding: utf-8 -*-

This informs the interpreter that it should treat the source code as UTF-8 (or any other encoding if this were the case) and not as ASCII, being able to use string literals, identifiers, comments, etc. that contain characters outside of the ASCII table. This must be done in both Python 2 and Python 3 when you want to use an encoding for the source code other than the one used by the interpreter by default.

    
answered by 19.06.2018 в 08:30