在Python中从任何字符串中移除非ASCII字符
>>> 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'
这也是我想要的结果。
我不太明白这个行为。有人能给我解释一下这里发生了什么吗?
编辑:我以为这样能让我理解事情,从而解决我在这里提到的真正程序问题:将包含非ASCII符号的Unicode对象转换为字符串对象(在Python中)
2 个回答
4
为什么使用decode("ascii")会得到一个unicode字符串呢?
因为这就是decode
的作用:它把像你这个ASCII字符串这样的字节字符串解码成unicode。
在你的第二个例子中,你试图“解码”一个已经是unicode的字符串,这样做是没有效果的。不过,要在终端打印它,Python必须把它编码成你默认的编码格式,也就是ASCII。但因为你没有明确进行这一步,也没有指定'ignore'参数,所以它就报错了,提示不能编码那些非ASCII字符。
理解这一切的关键是记住decode
是把编码过的字节字符串转换成Unicode,而encode
则是反过来的操作。可能更容易理解的是Unicode并不是一种编码方式。
4
其实很简单:.encode 是把 Unicode 对象转换成字符串,而 .decode 是把字符串转换成 Unicode。