Skip to main content
 首页 » 编程设计

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

2025年05月04日12lyhabc

print u'\xe4\xf6\xfc'.encode('utf-8') 
print unicode(u'\xe4\xf6\xfc') 

回溯:

盲枚眉 
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) 

python 外壳

>>>u"äöü".encode('utf-8') 
Unsupported characters in input 

请您参考如下方法:

在 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”编解码器转换)。