今天一位群友,Python3也報了類似的錯誤:
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()函數 來查看數據類型。