LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   python source code encoding (https://www.linuxquestions.org/questions/programming-9/python-source-code-encoding-4175443343/)

monsteriname 12-29-2012 03:15 AM

python source code encoding
 
Reading the python primer at http://docs.python.org/2/tutorial/interpreter.html

I found that "It is possible to use encodings different than ASCII in Python source files."

My question;

Is there a group of python programmers that do normally change encoding?
If so, for what reason(s)?

I did google it, and found a lot of interesting info about encoding, but didn't see the more specific info I'm after.

Thanks,

audriusk 12-29-2012 09:31 AM

This is done so often, that starting from Python 3 default encoding was changed to UTF-8. The reason is very simple: let's say you want to assign to a variable a Unicode string literal which contains some non-ASCII symbols in it. The example with Euro sign given in the docs section that you link to fits here perfectly:
Code:

foo = u'€'
If you want to write this line of code inside your .py file, you need to use an encoding that's different from ASCII and contains this symbol as well. But since Python interpreter treats string literals as ASCII text by default, you also need to inform it about the source file encoding by adding the following line at the beginning of your source file:
Code:

# -*- coding: utf-8 -*-
Otherwise you'll get an exception when trying to run your code:
Code:

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


monsteriname 12-29-2012 10:24 PM

Thank you audriusk for the great reply.


All times are GMT -5. The time now is 05:27 PM.