解码和unicode的区别?

2024-09-26 22:53:16 发布

您现在位置:Python中文网/ 问答频道 /正文

根据本试验:

# -*- 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()和{}之间没有区别:

^{pr2}$

我说得对吗?如果是这样,为什么我们有两种不同的方法来完成同一件事?我应该用哪一个?有什么细微的区别吗?


Tags: texttestformatlentypeunicodeequalutf
3条回答

比较这两个函数(herehere)的文档,这两个方法之间的差别似乎非常小。unicode函数被记录为

If encoding and/or errors are given, unicode() will decode the object which can either be an 8-bit string or a character buffer using the codec for encoding. The encoding parameter is a string giving the name of an encoding; if the encoding is not known, LookupError is raised. Error handling is done according to errors; this specifies the treatment of characters which are invalid in the input encoding. If errors is 'strict' (the default), a ValueError is raised on errors, ...

string.decode的描述是这样的

Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is 'strict', meaning that encoding errors raise UnicodeError. ...

因此,唯一的区别似乎是unicode也适用于字符缓冲区,并且对于无效输入返回的错误不同(ValueErrorUnicodeError)。另一个微小的区别在于向后兼容性:unicode被记录为“2.0版本中的新特性”,而string.decode是“2.2版本中的新特性”。在

综上所述,使用哪种方法似乎完全取决于口味。在

当您使用的值是str,并且使用的编码是Unicode字符集时,函数上没有区别。但是:

  1. u.decode(e)是一种方便的方法,在链式表达式中可能比调用unicode(s,e)更具可读性。

  2. 还有一些字符串转换与Unicode编码/解码无关,比如base64或{},它们可以在encode()/decode()中使用,但不能使用{}。(现在人们普遍认为,将它们放在与Unicode字符集相同的位置是错误的;它们在python3中被删除了,很可能会以单独的方法对结束。)

  3. 作为构造函数,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,所以函数返回的是相同的。如果您选择其他编码,它们应该返回不同的结果。在

相关问题 更多 >

    热门问题