python3报错 TypeError: can’t concat bytes to str 原因与解决方法

有时候,运行Python3会报错如下错误:

TypeError: can't concat bytes to str

中文翻译

类型错误:无法将字节连接到字符串

 

注意:

这里有时会报错这个:TypeError: Can't convert 'bytes' object to str implicitly

 

今天一位群友,Python3也报了类似的错误:

TypeError:can't concat str to bytes

TypeError:can't concat str to bytes

 

原因:

不管是报上面哪种错误?终其根本原因都是:类型不一致所造成的。

 

一、can't concat bytes to str 解决方法

解决方法也很简单,使用字节码的 decode()方法。

 

示例:

str = 'I am string'
byte = b' I am bytes'
s = str + byte
print(s)

报错“TypeError: can't concat bytes to str”。

 

解决方法:

s = str + byte.decode()

 

二、can't concat str to bytes 解决方法

为了好理解,我就简单拿几个示例来说吧!大家就能瞬间明白了。

 

示例1:

out = open('train_data.txt', 'w')
for sentence in sentences:
    out.write(sentence.encode("utf-8")+"\n")
print("done!")

报错“TypeError:can't concat str to bytes”

 

解决方法:

out.write(sentence.encode("utf-8")+b"\n")

原因:write函数参数需要为str类型,需转化为str。

 

示例2:

with open('fujieace.txt', 'w') as f:
    for line in docLst:
        f.write(line + '\n')

报错“TypeError:can't concat str to bytes”

 

解决方法:

这里只需要改两个地方,一个是把’w’改为‘wb’('wb'是字节写入。),一个是把‘\n’改为b’\n’。

with open('fujieace.txt', 'wb') as f:
    for line in docLst:
        f.write(line + b'\n')

 

总结:

如果当你不知道它是什么类型的时候?python里可直接通过 type()函数 来查看数据类型。

    A+
发布日期:2020年09月04日 15:36:06  所属分类:Python
最后更新时间:2023-03-02 05:05:27
付杰
  • ¥ 198.0元
  • 市场价:298.0元
  • ¥ 0.0元
  • 市场价:199.0元
  • ¥ 39.0元
  • 市场价:39.0元
  • ¥ 199.0元
  • 市场价:499.0元

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: