1. 引起问题的原因

有两种原因:

  • Python2和Python3在字符串编码上的区别。
  • 编码解码类型不一致

2. encode与decode函数

strbytes表示的是两种数据类型,str为字符串型,bytes为字节型。对str编码encode得到bytes,对bytes解码得到str,两者互为转换。而上面出现问题的一种原因是对str字符串使用了解码,显然是猪头不对马尾。

txt = '你好,shiyi,很感谢你陪伴我的日子'
#str->bytes encode
txt = txt.encode('utf-8')
print(type(txt))
#bytes->str decode
txt = txt.decode('utf-8')
print(type(txt))

# results
<class 'bytes'>
<class 'str'>
Process finished with exit code 0

3. python2与python3的编码方式

  • Python3的str 默认不是bytes,所以不能decode,只能先encode转为bytes,再decode
  • python2的str 默认是bytes,所以能decode

4. 解决方法

  • 对于第一种原因:删除decode(‘utf-8’)或者使用‘str’.encode(‘utf-8’). decode(‘utf-8’) 先编码成bytes,再解码成字符串
  • 对于第二种:各种编码方式尝试解决:utf-8,gbk,ISO-8859-1,gb2312
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐