Skip to main content
 首页 » 编程设计

python之增加对 Python 中 Unicode 的理解 (2.7)

2025年05月04日16sxdcgaq8080

我在程序中观察到这一点

# -*- coding: utf-8 -*- 
words = ['artists', 'Künstler', '艺术家', 'Митець'] 
for word in words: 
    print word, type(word) 

将字符串完全限定为 unicode 字符串并不是绝对必要的:

words = ['artist', u'Künstler', u'艺术家', u'Митець'] 

不同的字母表在没有“u”前缀的情况下处理得很好。

因此,一旦指定了 coding: utf-8,所有字符串都将以 Unicode 编码。是真的吗?

  • 或者仅当字符串不再适合范围 (128) 时才使用 unicode?
  • 为什么 type(word)报告 <str>在所有情况下?不是 unicode一个特殊的数据类型?

请您参考如下方法:

也许这样会更清楚:

# -*- coding: utf-8 -*- 
words = ['artists', 'Künstler', '艺术家', 'Митець'] 
for word in words: 
    print word, type(word), repr(word) 
words = [u'artists', u'Künstler', u'艺术家', u'Митець'] 
for word in words: 
    print word, type(word), repr(word) 

输出:

artists <type 'str'> 'artists' 
Künstler <type 'str'> 'K\xc3\xbcnstler' 
艺术家 <type 'str'> '\xe8\x89\xba\xe6\x9c\xaf\xe5\xae\xb6' 
Митець <type 'str'> '\xd0\x9c\xd0\xb8\xd1\x82\xd0\xb5\xd1\x86\xd1\x8c' 
artists <type 'unicode'> u'artists' 
Künstler <type 'unicode'> u'K\xfcnstler' 
艺术家 <type 'unicode'> u'\u827a\u672f\u5bb6' 
Митець <type 'unicode'> u'\u041c\u0438\u0442\u0435\u0446\u044c' 

在第一种情况下,您获得的字节字符串以已声明的 UTF-8 源编码进行编码。它们只会在 UTF-8 终端上正确显示。

在第二种情况下,您将获得 Unicode 字符串。它们将在任何编码支持这些字符的终端上正确显示。

以下是字符串在 Windows 代码页 437 控制台上的显示方式,使用 Python 环境变量配置 Python 以替换不受支持的字符,而不是为它们引发默认的 UnicodeEncodeError 异常:

c:\>set PYTHONIOENCODING=cp437:replace 
c:\>py -2 x.py 
artists <type 'str'> 'artists' 
K├╝nstler <type 'str'> 'K\xc3\xbcnstler' 
艺术家 <type 'str'> '\xe8\x89\xba\xe6\x9c\xaf\xe5\xae\xb6' 
Митець <type 'str'> '\xd0\x9c\xd0\xb8\xd1\x82\xd0\xb5\xd1\x86\xd1\x8c' 
artists <type 'unicode'> u'artists' 
Künstler <type 'unicode'> u'K\xfcnstler' 
??? <type 'unicode'> u'\u827a\u672f\u5bb6' 
?????? <type 'unicode'> u'\u041c\u0438\u0442\u0435\u0446\u044c' 

字节字符串大多是垃圾,但 Unicode 字符串是合理的,因为该代码页不支持中文和俄语。