Python 字符串编码

标签 python string encode python-2.x

我有这个代码

att=att.replace("à","a")

但是我收到了这个错误...

  att=att.replace("à","a")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

我该如何解决?

最佳答案

不要将 unicode 与字节字符串混合。 Python2 进行隐式转换,而 Python3 则不进行。即使您不使用 Python3,避免混合两者也是一个好习惯。

在Python2中,如果att是unicode,那么

att.replace("à","a")

在尝试之前隐式尝试将“à”“a”解码为unicode替换 att 中的 "à"。 Python2 使用 ascii (默认情况下)进行隐式解码。

"à".decode('ascii') 引发 UnicodeDecodeError: 'ascii' 编解码器无法解码位置 0 中的字节 0xc3:序数不在范围内(128).

要修复此错误,由于 attunicode,因此 att.replace 的参数也应该是 unicode:

att.replace(u"à",u"a")

关于Python 字符串编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32056220/

相关文章:

python - 如何在 Ubuntu 中以 sudo 权限运行 PyQt 应用程序并保持正常用户风格

javascript - 是否可以对字符串进行子串化,但隐藏整个字符串?

c++ - 从文件到 float 的文本

python - UnicodeEncodeError : 'charmap' codec can't encode character (in Python 3. 3)

python - 在keras中添加卷积层给出错误

python - 如何通过 excel 为我的物理实验课使用 python、PyLab、NumPy 等

Python程序随机挂起

C++ 重载 + 运算符,以便始终连接各种字符串

linux - Linux 上的代码页转换支持

mysql - MD5 与密码编码?