I'm using OSX Yosemite on a Macbook Pro with a UK keyboard. When I type # into a Python file (using Alt+3) I sometimes, but not always, see this syntax error when I try to run the Python file:

SyntaxError: Non-ASCII character '\xc2' in file

I can usually fix it by copying and pasting a hash character from elsewhere in the file.

I could fix it by manually setting every Python I ever work on to UTF-8 encoding:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

but that's not really practical when I'm working on other people's code.

Is there any way I can reset the value of this key to an ASCII-friendly # to avoid this error?

  • 1
    Which editor are you using? – Matteo Mar 20 '15 at 11:47
  • Sorry, I'm using Sublime. – Richard Mar 23 '15 at 18:24
  • (That's Sublime Text 3.) – Richard Apr 22 '15 at 11:21
  • Did you ever make any progress? This happens to me too and you're the only one I've found with the same problem. Wracking my brain trying to work it out, it's like it inserts an invisible character which Python bails on. You using the wireless keyboard? – AndyC Jul 28 '15 at 11:50

There is a twofold problem at work here. One cause can be a .DS_Store file containing UTF-8 characters inside of it in the local directory that is being read behind the scenes. If this is the case, simply adding the encoding to the top of the file will fix it:

# coding: utf-8

A second cause can be how we get code from one place to another. If you are on a Mac and you copy code and then paste it into a file with cat as follows:

$ cat > file.py       (<-- Hit Command-V to paste while doing this)

This can lead to an interesting issue. The formatting, more specifically the leading space, looks Pythonic. However, your tabs have been replaced with something containing wide characters that no amount of character encoding configuration can seem to resolve. If you face this, simply replace all of the leading whitespace and Python will be very happy.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.