解码,如果它不是unicode

Man*_*ron 13 python unicode encoding utf-8

我希望我的函数接受一个可以是unicode对象或utf-8编码字符串的参数.在我的函数中,我想将参数转换为unicode.我有这样的事情:

def myfunction(text):
    if not isinstance(text, unicode):
        text = unicode(text, 'utf-8')

    ...
Run Code Online (Sandbox Code Playgroud)

是否可以避免使用isinstance?我正在寻找更友善的鸭子.

在我的解码实验中,我遇到了几种奇怪的Python行为.例如:

>>> u'hello'.decode('utf-8')
u'hello'
>>> u'cer\xf3n'.decode('utf-8')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in po
sition 3: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

要么

>>> u'hello'.decode('utf-8')
u'hello' 12:11
>>> unicode(u'hello', 'utf-8')
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: decoding Unicode is not supported
Run Code Online (Sandbox Code Playgroud)

顺便说说.我正在使用Python 2.6

unu*_*tbu 19

您可以尝试使用'utf-8'编解码器对其进行解码,如果这不起作用,则返回该对象.

def myfunction(text):
    try:
        text = unicode(text, 'utf-8')
    except TypeError:
        return text

print(myfunction(u'cer\xf3n'))
# cerón
Run Code Online (Sandbox Code Playgroud)

当您使用unicode对象并decode使用'utf-8'编解码器调用其方法时,Python首先尝试将unicode对象转换为字符串对象,然后调用字符串对象的decode('utf-8')方法.

有时从unicode对象到字符串对象的转换失败,因为Python2默认使用ascii编解码器.

因此,通常,永远不要尝试解码unicode对象.或者,如果必须尝试,请将其捕获到try..except块中.可能有一些编解码器解码unicode对象在Python2中工作(见下文),但它们已在Python3中删除.

有关此问题的有趣讨论,请参阅此Python错误凭证,以及Guido van Rossum的博客:

"我们采用了略微不同的编解码方法:在Python 2中,编解码器可以接受Unicode或8位作为输入并产生输出,在Py3k中,编码总是从Unicode(文本)字符串转换为字节数组,并且解码总是朝着相反的方向.这意味着我们必须删除一些不适合此模型的编解码器,例如rot13,base64和bz2(这些转换仍然受支持,而不是通过编码/ decode API)."