python - “需要一个类似字节的对象”,但 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
解决方案
您用来替换它的必须是类似字节的对象。
因此,您应该使用要替换的字符的字节表示。(在下面试试这个)
text = text.replace(b' ', b'_')
但是,请知道这在 python 3.6 中已修复,因此如果可能的话,您应该更新到此版本。
推荐阅读
- reactjs - 根据从 API 获取的数组重复渲染组件
- c# - 这是链接异步调用(C#/WPF)的正确方法吗?
- windows - 无法连接到 Docker 守护程序 WINDOWS
- oracle - 如何使用 oracle 数据库 10g 安装 oracle APEX 20.1
- linux - 如果我们的搜索/替换模式包含多个正斜杠,如何在 Vim/Linux 中搜索和替换?
- regex - 在 Scala 中匹配 IP 地址
- python - 如何从不和谐的成员那里获取角色名称
- python - Sympy.plot 不为 x > 0 绘制平方根图
- c# - 无法访问容器外的文件夹
- javascript - Node.js For() 循环未按预期工作