Bjo*_*orn 4 python unicode macos terminal
我有terminal.app设置接受utf-8和在bash我可以键入unicode字符,复制并粘贴它们,但如果我启动python shell我不能,如果我尝试解码unicode我得到错误:
>>> wtf = u'\xe4\xf6\xfc'.decode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
>>> wtf = u'\xe4\xf6\xfc'.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/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-2: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
谁知道我做错了什么?
sth*_*sth 18
我认为整个地方都存在编码/解码混淆.你从一个unicode对象开始:
u'\xe4\xf6\xfc'
Run Code Online (Sandbox Code Playgroud)
这是一个unicode对象,三个字符是"äöü"的unicode代码点.如果你想把它们变成Utf-8,你必须对它们进行编码:
>>> u'\xe4\xf6\xfc'.encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
Run Code Online (Sandbox Code Playgroud)
由此产生的六个字符是"äöü"的Utf-8表示.
如果您调用decode(...)
,则尝试将字符解释为仍需要转换为unicode的某些编码.由于它已经是Unicode,这不起作用.您的第一个调用尝试Ascii转换为Unicode,第二个调用Utf-8转换为Unicode.既然u'\xe4\xf6\xfc'
既不是有效的Ascii也不是有效的Utf-8,这些转换尝试都失败了.
进一步的混淆可能来自于'\xe4\xf6\xfc'
"äöü"的Latin1/ISO-8859-1编码这一事实.如果你编写一个普通的python字符串(没有标记为unicode的前导"u"),你可以将它转换为一个unicode对象decode('latin1')
:
>>> '\xe4\xf6\xfc'.decode('latin1')
u'\xe4\xf6\xfc'
Run Code Online (Sandbox Code Playgroud)