4
>>> teststring = 'aõ'
>>> type(teststring)
<type 'str'>
>>> teststring
'a\xf5'
>>> print teststring
aõ
>>> teststring.decode("ascii", "ignore")
u'a'
>>> teststring.decode("ascii", "ignore").encode("ascii")
'a'

这是我真正希望它在我删除非 ascii 字符时在内部存储的内容。为什么 decode("ascii 会给出一个 unicode 字符串?

>>> teststringUni = u'aõ'
>>> type(teststringUni)
<type 'unicode'>
>>> print teststringUni
aõ
>>> teststringUni.decode("ascii" , "ignore")

Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    teststringUni.decode("ascii" , "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf5' in position 1: ordinal not in range(128)
>>> teststringUni.decode("utf-8" , "ignore")

Traceback (most recent call last):
  File "<pyshell#81>", line 1, in <module>
    teststringUni.decode("utf-8" , "ignore")
  File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf5' in position 1: ordinal not in range(128)
>>> teststringUni.encode("ascii" , "ignore")
'a'

这又是我想要的。我不明白这种行为。有人可以向我解释这里发生了什么吗?

编辑:我认为这会让我明白一些事情,所以我可以解决我在这里陈述的真正的程序问题: Converting Unicode objects with non-ASCII symbols in them into strings objects (in Python)

4

2 回答 2

4

为什么 decode("ascii") 会给出一个 unicode 字符串?

因为这decode就是用途:它将像您的 ASCII 一样的字节字符串解码为 un​​icode。

在您的第二个示例中,您试图“解码”一个已经是 unicode 的字符串,它没有任何效果。但是,要将其打印到您的终端,Python 必须将其编码为您的默认编码,即 ASCII - 但由于您没有明确完成该步骤,因此没有指定“忽略”参数,它会引发错误无法对非 ASCII 字符进行编码。

所有这一切的诀窍是记住decode接受编码的字节串并将其转换为 Unicode,然后encode进行相反的操作。如果您了解Unicode 不是一种编码,这可能会更容易。

于 2010-09-08T13:25:03.123 回答
4

很简单:.encode 将 Unicode 对象转换为字符串,.decode 将字符串转换为 Unicode。

于 2010-09-08T13:25:39.640 回答