TypeError: can only concatenate str (not "bytes") to str
在Python中,遇到错误 TypeError: can only concatenate str (not "bytes") to str 通常意味着你尝试将字符串(str)和字节串(bytes)进行连接,但这是不允许的。在Python 3中,字符串和字节串是不同的数据类型,不能直接相加或连接。
解决方法
1. 确保两边都是字符串或都是字节串
如果需要将字符串和字节串连接,则先将字节串转换为字符串或字符串转换为字节串,然后再进行连接。
字节串和字符串:
bytes_data = b"hello"
str_data = " world"
# 将字节串转换为字符串
str_data_from_bytes = bytes_data.decode('utf-8') # 假设字节串是UTF-8编码
result = str_data_from_bytes + str_data
print(result) # 输出: hello world。