Tôi muốn hàm của tôi lấy một đối số có thể là đối tượng unicode hoặc chuỗi được mã hóa utf-8. Bên trong hàm của tôi, tôi muốn chuyển đối số thành unicode. Tôi có một cái gì đó như thế này:Giải mã nếu nó không phải là unicode
def myfunction(text):
if not isinstance(text, unicode):
text = unicode(text, 'utf-8')
...
Có thể tránh việc sử dụng isinstance không? Tôi đang tìm kiếm thứ gì đó thân thiện với vịt hơn.
Trong khi thử nghiệm của tôi với giải mã, tôi đã chạy vào một số hành vi kỳ lạ của Python. Ví dụ:
>>> 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)
Hoặc
>>> 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
Bằng cách này. Tôi đang sử dụng Python 2.6
Bạn có thể muốn xem xét câu hỏi này: [Python UnicodeDecodeError - Tôi hiểu nhầm Unicode?] (Http://stackoverflow.com/questions/368805/) – tzot