'unicode'和'encode'之间有什么关系

zjm*_*126 1 python unicode

print u'\xe4\xf6\xfc'.encode('utf-8')
print unicode(u'\xe4\xf6\xfc')
Run Code Online (Sandbox Code Playgroud)

追溯:

???
Traceback (most recent call last):
  File "D:\zjm_code\a.py", line 6, in <module>
    print unicode(u'\xe4\xf6\xfc')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

python shell

>>>u"äöü".encode('utf-8')
Unsupported characters in input
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 12

在Python 2中:

case a: (unicode object).encode(somecodec) -> string of bytes
case b: (string of bytes).decode(somecodec) -> unicode object
case c: unicode(string of bytes, somecodec) -> unicode object

案例b和c是相同的.在这三种情况中的每一种情况下,您可以省略编解码器名称:然后默认为'ascii'ASCII解码器(仅支持128个ASCII字符 - 否则将获得异常).

每当箭头左侧需要"字符串"时,您可以传递一个unicode对象(它使用'ascii'编解码器转换).

只要箭头左侧需要'unicode',就可以传递一串字节(用'ascii'编解码器转换).


sth*_*sth 6

编码错误:

print unicode(u'\xe4\xf6\xfc')
Run Code Online (Sandbox Code Playgroud)

这里的unicode()调用没有任何作用,因为它的参数已经是一个unicode对象.print然后尝试输出该unicode对象,并print希望将其转换为终端编码中的字符串.但python似乎不知道您的终端使用哪种编码,因此与Ascii的"安全"替代方案一致.

由于u'\xe4\xf6\xfc'无法在Ascii中表示,因此会导致编码错误.

Unicode,编码和解码:

通常encode()将unicode对象转换为具有特定字符编码(如UTF-8或ISO-8859-1)的字符串.每个unicode代码点都转换为该编码中的字节序列:

>>> u'\xe4\xf6\xfc'.encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
Run Code Online (Sandbox Code Playgroud)

相反decode(),它将特定编码中的字符串转换为包含相应unicode代码点的unicode对象.

>>> '\xc3\xa4\xc3\xb6\xc3\xbc'.decode('utf-8')
u'\xe4\xf6\xfc'
Run Code Online (Sandbox Code Playgroud)

印刷:

print使用字符串参数只打印该字符串的原始字节.如果这导致所需的输出取决于终端的字符编码.

>>> print '\xc3\xa4\xc3\xb6\xc3\xbc'  # utf-8 encoding on utf-8 terminal
äöü
>>> print '\xe4\xf6\xfc'              # same encoded as latin-1
???
Run Code Online (Sandbox Code Playgroud)

当给定unicode参数时,print首先尝试在终端编码中对unicode对象进行编码.这只有在python猜测终端的正确编码并且该编码实际上可以代表unicode对象的所有字符时才有效.否则编码会抛出异常或输出包含错误的字符.

>>> print u'\xe4\xf6\xfc'             # it correctly assumes a utf-8 terminal
äöü
Run Code Online (Sandbox Code Playgroud)