KDecker KDecker - 9 months ago 88
Python Question

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

I am writing some python code and I am receiving the error message as in the title, from searching this has to do with the character set.

Here is the line that causes the error

hc = HealthCheck("instance_health", interval=15, target808="HTTP:8080/index.html")

I cannot figure out what character is not in the ANSI ASCII set? Furthermore searching "\xe2" does not give anymore information as to what character that appears as. Which character in that line is causing the issue?

I have also seen a few fixes for this issue but I am not sure which to use. Could someone clarify what the issue is (python doesn't interpret unicode unless told to do so?), and how I would clear it up properly?

Here are all the lines near the one that errors

def createLoadBalancer():
conn = ELBConnection(creds.awsAccessKey, creds.awsSecretKey)
hc = HealthCheck("instance_health", interval=15, target808="HTTP:8080/index.html")
lb = conn.create_load_balancer('my_lb', ['us-east-1a', 'us-east-1b'],[(80, 8080, 'http'), (443, 8443, 'tcp')])
return lb

Answer Source

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"