【发布时间】:2011-04-20 22:36:39
【问题描述】:
我希望我的函数接受一个可以是 unicode 对象或 utf-8 编码字符串的参数。在我的函数内部,我想将参数转换为 unicode。我有这样的事情:
def myfunction(text):
if not isinstance(text, unicode):
text = unicode(text, 'utf-8')
...
是否可以避免使用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)
或者
>>> 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
顺便说一句。我正在使用 Python 2.6
【问题讨论】:
标签: python unicode encoding utf-8