torsdag den 29. oktober 2009

Python UTF-8 for non english characters

Configure module
First make sure your python module is saved as UTF-8

Next, in the top of your python module add the setting:

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


this will tell the compiler to use UTF-8 instead of OS specific

Prefix a 'u' for all strings
print u"rødgrød med fløde"

- will work

print "red porridge with cream"

- wil work because no non-english characters are present
(or whatever difference between your OS and UTF-8)

print "rødgrød med fløde"


- will not work because the encoding is misinterpreted

Entire python script

# -*- coding: utf-8 -*-
print u"rødgrød med fløde"