Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: Non-ASCII character '\xc2' in file, but no encoding declared in Python 2.7 [duplicate]

I tried this code in Python 2:

def NewFunction():
    return '£'

But I get an error message that says:

SyntaxError: Non-ASCII character '\xa3' in file '...' but no encoding declared;
see http://www.python.org/peps/pep-0263.html for details

Similarly, in Python 3, if I write the same code and save it with Latin-1 encoding, I get:

SyntaxError: Non-UTF-8 code starting with '\xa3' in file ... on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

How can I use a pound sign in string literals in my code?


See also: Correct way to define Python source code encoding for details about whether an encoding declaration is needed and how it should be written. Please use that question to close duplicates asking about how to write the declaration, and this one for questions asking about resolving the error.

like image 488
SNIFFER_dog Avatar asked Mar 06 '26 16:03

SNIFFER_dog


2 Answers

I'd recommend reading that PEP the error gives you. The problem is that your code is trying to use the ASCII encoding, but the pound symbol is not an ASCII character. Try using UTF-8 encoding. You can start by putting # -*- coding: utf-8 -*- at the top of your .py file. To get more advanced, you can also define encodings on a string by string basis in your code. However, if you are trying to put the pound sign literal in to your code, you'll need an encoding that supports it for the entire file.

like image 105
Silas Ray Avatar answered Mar 09 '26 06:03

Silas Ray


Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
like image 41
Timothée HENRY Avatar answered Mar 09 '26 04:03

Timothée HENRY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!