The Python Oracle

Python "SyntaxError: Non-ASCII character '\xe2' in file"

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Music Box Puzzles

--

Chapters
00:00 Question
01:19 Accepted answer (Score 159)
01:51 Answer 2 (Score 323)
02:08 Answer 3 (Score 43)
02:24 Answer 4 (Score 31)
02:47 Thank you

--

Full question
https://stackoverflow.com/questions/2163...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 331


If you are just trying to use UTF-8 characters or don't care if they are in your code, add this line to the top of your .py file

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



ACCEPTED ANSWER

Score 161


You've got a stray byte floating around. You can find it by running

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

where you should replace "x.py" by the name of your program. You'll see the line number and the offending line(s). For example, after inserting that byte arbitrarily, I got:

4 "\xe2        lb = conn.create_load_balancer('my_lb', ['us-east-1a', 'us-east-1b'],[(80, 8080, 'http'), (443, 8443, 'tcp')])\n"



ANSWER 3

Score 32


\xe2 is the '-' character, it appears in some copy and paste it uses a different equal looking '-' that causes encoding errors. Replace the '-'(from copy paste) with the correct '-' (from you keyboard button).




ANSWER 4

Score 24


Change the file character encoding,

put below line to top of your code always

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