gpt4 book ai didi

python - 从 Python 中的任何给定字符串类型中删除非 ascii 字符

转载 作者:太空狗 更新时间:2023-10-30 02:14:10 28 4
gpt4 key购买 nike

>>> teststring = 'aõ'
>>> type(teststring)
<type 'str'>
>>> teststring
'a\xf5'
>>> print teststring

>>> teststring.decode("ascii", "ignore")
u'a'
>>> teststring.decode("ascii", "ignore").encode("ascii")
'a'

当我删除非 ascii 字符时,这是我真正希望它在内部存储的内容。为什么解码(“ascii给出了一个unicode字符串?

>>> teststringUni = u'aõ'
>>> type(teststringUni)
<type 'unicode'>
>>> print teststringUni

>>> 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)

最佳答案

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

关于python - 从 Python 中的任何给定字符串类型中删除非 ascii 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3667875/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com