Python error: SyntaxError: Non-ASCII character

You will already know that I’m a heavy Python user. Python is the perfect language for me for a fast and easy way to script some useful and helpful tools. Something which I came across a longer time ago: Python has some problems with umlauts and other special characters.

What is it all about?

In Python 3 you can use special characters such as the German umlauts all the time. You will not run into any issue. But if you have to use Python 2, you will run into serious problems. For example, the following code will run with Python 3 but will produce errors with Python 2:

# This are german umlauts äöü
print("foo")

While we will get the expected result with Python 3, Python 2 will gives you the following error:

SyntaxError: Non-ASCII character '\xc3' in file foo.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

This error indicates, that Python 2 was unable to encode the umlauts which are written down in the script file. But there is a solution available …

The Solution

The solution is rather simple. Just put this into the first line of your Python script file and you will be read to go again:

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

For the example above the code will now look like this:

# -*- coding: utf-8 -*-
# This are german umlauts äöü
print("foo")

Save and rerun your script. Python 2 will now be able to work with it as well.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s