一个简单的例子unicode的变量:Python的解码与非ASCII字符或不
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import traceback
e_u = u'abc'
c_u = u'中国'
print sys.getdefaultencoding()
try:
print e_u.decode('utf-8')
print c_u.decode('utf-8')
except Exception as e:
print traceback.format_exc()
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
try:
print e_u.decode('utf-8')
print c_u.decode('utf-8')
except Exception as e:
print traceback.format_exc()
输出:
ascii
abc
Traceback (most recent call last):
File "test_codec.py", line 15, in <module>
print c_u.decode('utf-8')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
utf-8
abc
中国
一些问题困扰了我几天,当我想彻底了解编解码器在Python中,我想确保我认为是正确的:
根据
ascii
de故障编码,u'abc'.decode('utf-8')
没有错误,但是u'中国'.decode('utf-8')
有错误。我觉得做
u'中国'.decode('utf-8')
,Python的检查,发现当u'中国'
是unicode的,所以尽量做到u'中国'.encode(sys.getdefaultencoding())
,这样会导致问题,而例外的是UnicodeEncodeError
,不是错误的时候解码。但
u'abc'
与'abc'
(< 128)的代码点相同,所以没有错误。在Python 2.x中,python内部存储变量值如何?如果字符串< 128中的所有字符视为
ascii
,如果> 128,则视为utf-8
?In [4]: chardet.detect('abc') Out[4]: {'confidence': 1.0, 'encoding': 'ascii'} In [5]: chardet.detect('abc中国') Out[5]: {'confidence': 0.7525, 'encoding': 'utf-8'} In [6]: chardet.detect('中国') Out[6]: {'confidence': 0.7525, 'encoding': 'utf-8'}
我知道应该使用'encode',我的问题是,为什么在u'abc”使用解码都没有问题,而且我认为是正确的? – 2015-01-21 09:22:09
请参阅我的答案的第二部分,其中描述了unicode.decode()在内部的行为。这应该清楚为什么'u'abc'.decode()'意外地工作。 – vog 2015-01-21 09:38:33
你说的第2部分,我认为错误:'从unicode字符串的任何隐式转换为字节字符串,总是使用ASCII字符set.'。请参阅我问的示例代码,如果将默认编码更改为utf-8,则可以。 – 2015-01-21 14:12:33