,python,python-3.x,character-encoding"/>

首页 > 解决方案 > “需要一个类似字节的对象”,但 type(var) 返回

问题描述

我必须进行一些文本处理并且在编码方面遇到问题:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 11: invalid start byte

所以我做了:

text = text.encode('utf-8').strip()

但是稍后在代码中我必须这样做:

text = text.replace(' ', '_')

这给了我以下错误:

TypeError: a bytes-like object is required, not 'str'

但此时的类型text字节。我在 python shell 上运行它,如下所示,在encode命令之后,结果是 class 的对象bytes

在此处输入图像描述

这里到底发生了什么,我该如何解决?我正在使用 Python 3.5.2

标签: pythonpython-3.xcharacter-encoding

解决方案


您用来替换它的必须是类似字节的对象。

因此,您应该使用要替换的字符的字节表示。(在下面试试这个)

text = text.replace(b' ', b'_')

但是,请知道这在 python 3.6 中已修复,因此如果可能的话,您应该更新到此版本。


推荐阅读