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
我们尝试使用加法
+
运算符连接字节对象和导致错误的字符串。
左侧和右侧的值需要是兼容的类型。
解决错误的一种方法是将字节对象转换为字符串。
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”。 要解决此错误,请在连接字符串之前将字节对象解码为字符串。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。