根据本试验:
# -*- coding: utf-8 -*-
ENCODING = 'utf-8'
# what is the difference between decode and unicode?
test_cases = [
'aaaaa',
'ááááá',
'ℕℤℚℝℂ',
]
FORMAT = '%-10s %5d %-10s %-10s %5d %-10s %10s'
for text in test_cases :
decoded = text.decode(ENCODING)
unicoded = unicode(text, ENCODING)
equal = decoded == unicoded
print FORMAT % (decoded, len(decoded), type(decoded), unicoded, len(unicoded), type(unicoded), equal)
.decode()
和{
我说得对吗?如果是这样,为什么我们有两种不同的方法来完成同一件事?我应该用哪一个?有什么细微的区别吗?
比较这两个函数(here和here)的文档,这两个方法之间的差别似乎非常小。
unicode
函数被记录为而
string.decode
的描述是这样的因此,唯一的区别似乎是
unicode
也适用于字符缓冲区,并且对于无效输入返回的错误不同(ValueError
与UnicodeError
)。另一个微小的区别在于向后兼容性:unicode
被记录为“2.0版本中的新特性”,而string.decode
是“2.2版本中的新特性”。在综上所述,使用哪种方法似乎完全取决于口味。在
当您使用的值是
str
,并且使用的编码是Unicode字符集时,函数上没有区别。但是:u.decode(e)
是一种方便的方法,在链式表达式中可能比调用unicode(s,e)
更具可读性。还有一些字符串转换与Unicode编码/解码无关,比如},它们可以在}。(现在人们普遍认为,将它们放在与Unicode字符集相同的位置是错误的;它们在python3中被删除了,很可能会以单独的方法对结束。)
base64
或{encode()
/decode()
中使用,但不能使用{作为构造函数,
unicode()
可以采用str
以外的类型,您可能希望为这些类型生成Unicode字符串表示。解码:
使用为编码注册的编解码器解码字符串。编码默认为默认字符串编码。
http://docs.python.org/2/library/stdtypes.html?#str.decode
unicode:
返回object[…]的Unicode字符串版本。
请参见:http://docs.python.org/2/library/functions.html#unicode
因为您的编码是UTF-8,所以函数返回的是相同的。如果您选择其他编码,它们应该返回不同的结果。在
相关问题 更多 >
编程相关推荐