我有一个带有UTF-8头部的虚拟Python模块,其代码如下:
# -*- coding: utf-8 -*-
a = "á"
print type(a), a
这将输出:
<type 'str'> á
但是我认为在Python模块中声明的所有字符串文字都应该自动成为unicode
类型,而不是str
类型。我错过了什么还是这是正确的行为?
为了将a
作为Unicode字符串获取,我使用:
a = u"á"
但这似乎不太“礼貌”,也不实用。有更好的选择吗?
我有一个带有UTF-8头部的虚拟Python模块,其代码如下:
# -*- coding: utf-8 -*-
a = "á"
print type(a), a
这将输出:
<type 'str'> á
但是我认为在Python模块中声明的所有字符串文字都应该自动成为unicode
类型,而不是str
类型。我错过了什么还是这是正确的行为?
为了将a
作为Unicode字符串获取,我使用:
a = u"á"
# -*- coding: utf-8 -*-
不会将字符串字面量转换为Unicode。以这个例子为例,我有一个带有阿拉伯语注释和字符串的文件,该文件是utf-8编码:
# هذا تعليق عربي
print type('نص عربي')
如果我运行它,它会抛出一个SyntaxError
异常:
SyntaxError: Non-ASCII character '\xd9' in file file.py
on line 2, but no encoding declared;
see http://www.python.org/peps/pep-0263.html for details
# -*-coding: utf-8 -*-
# هذا تعليق عربي
print type('نص عربي')
<type 'str'>
。# -*-coding: utf-8 -*-
# هذا تعليق عربي
print type(u'نص عربي')
str
正常打印,但处理这些类型的字符串会导致运行时错误,不是吗?因此,如果使用非 ASCII 字符,除了标题之外,始终使用 u
处理潜在冲突的字符串。我说得对吗? - Caumonsprint len(u'أ'); print len('أ')
。 - user1129665u
:) 谢谢! - Caumons$ cat /tmp/test.py
example = '☃'
$ python2.7 /tmp/test.py
File "/tmp/test.py", line 1
SyntaxError: Non-ASCII character '\xe2' in file /tmp/test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
unicode_snowman = '\xe2\x98\x83'.decode('utf8')
unicode_snowman = unichr(0x2603)
这并不意味着所有字面值都是Unicode,只是指出了如何解码Unicode字面值。To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:
# coding=<encoding name> or (using formats recognized by popular editors) #!/usr/bin/python # -*- coding: <encoding name> -*- or #!/usr/bin/python # vim: set fileencoding=<encoding name> :
unicode
函数或u
前缀将字面值设置为Unicode。
u'...'
unicode字面量有什么不得体的地方?你为什么感觉它不实用? - Martijn Pietersu
声明它们。标题编码适用于这些Unicode字符串实际上如何编码,但不影响str
。 - Caumonsfrom __future__ import unicode_literals
会将所有的字面值转换为Unicode字面值(适用于Python2.6和2.7)。 - Sven Marnach