Alex Rivera | Logout

Why declare unicode by string in python?

Asked 2010-07-03T03:28:14.900
123

I'm still learning python and I have a doubt:

In python 2.6.x I usually declare encoding in the file header like this (as in PEP 0263)

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

After that, my strings are written as usual:

a = "A normal string without declared Unicode"

But everytime I see a python project code, the encoding is not declared at the header. Instead, it is declared at every string like this:

a = u"A string with declared Unicode"

What's the difference? What's the purpose of this? I know Python 2.6.x sets ASCII encoding by default, but it can be overriden by the header declaration, so what's the point of per string declaration?

Addendum: Seems that I've mixed up file encoding with string encoding. Thanks for explaining it :)

Edit
Report

1 Answer

7

The header definition is to define the encoding of the code itself, not the resulting strings at runtime.

putting a non-ascii character like ۲ in the python script without the utf-8 header definition will throw a warning

error

answered 2010-07-03T03:35:01.233

Your Answer