Python 中 TypeError: can’t concat str to bytes 错误

当我们尝试连接字节对象和字符串时,会出现 Python “TypeError: can’t concat str to bytes”。 要解决此错误,请在连接字符串之前将字节对象解码为字符串。

下面是产生上面错误的示例代码

my_bytes = b'hello '

my_str = 'world'

# ⛔️ TypeError: can't concat str to bytes
result = my_bytes + my_str

Python 中 TypeError: can't concat str to bytes 错误

我们尝试使用加法 + 运算符连接字节对象和导致错误的字符串。

左侧和右侧的值需要是兼容的类型。

解决错误的一种方法是将字节对象转换为字符串。

my_bytes = b'hello '

my_str = 'world'

# 👇️ decode bytes object
result = my_bytes.decode('utf-8') + my_str

print(result)  # 👉️ "hello world"

bytes.decode() 方法返回从给定字节解码的字符串。 默认编码是 utf-8

或者,我们可以将字符串编码为字节对象。

my_bytes = b'hello '

my_str = 'world'

result = my_bytes + my_str.encode('utf-8')

print(result)  # 👉️ b"hello world"

str.encode() 方法将字符串的编码版本作为字节对象返回。 默认编码为 utf-8

无论哪种方式,您都必须确保加法 + 运算符左侧和右侧的值是兼容的类型(例如两个字符串)。

一旦将字节对象转换为字符串,就可以使用格式化的字符串文字。

# 👇️ decode bytes object
my_bytes = b'hello '.decode('utf-8')

my_str = 'world'

result = f'{my_bytes} {my_str}'

print(result)  # "hello  world"

格式化字符串文字(f-strings)让我们通过在字符串前面加上 f 来在字符串中包含表达式。

确保将表达式包裹在花括号 – {expression} 中。

如果我们不确定变量存储什么类型,请使用内置的 type() 类。

# 👇️ decode bytes object
my_bytes = b'hello '
print(type(my_bytes))  # 👉️ <class 'bytes'>
print(isinstance(my_bytes, bytes))  # 👉️ True

my_str = 'world'
print(type(my_str))  # 👉️ <class 'str'>
print(isinstance(my_str, str))  # 👉️ True

类型类返回对象的类型。

如果传入的对象是传入类的实例或子类,则 isinstance 函数返回 True


总结

当我们尝试连接字节对象和字符串时,会出现 Python “TypeError: can’t concat str to bytes”。 要解决此错误,请在连接字符串之前将字节对象解码为字符串。