Python 中TypeError: decoding str is not supported 错误

当我们尝试多次将对象转换为字符串或在调用 str() 类时设置编码关键字参数而不提供字节对象时,会出现 Python“TypeError: decoding str is not supported”。

看下面的代码

# ⛔️ TypeError: decoding str is not supported
str('hello', str(123))

# ⛔️ TypeError: decoding str is not supported
str('abc', encoding='utf-8')

Python 中TypeError: decoding str is not supported 错误

第一个示例对 str() 函数进行了两次调用,一个嵌套在另一个中。在第二个示例中,我们在不提供有效字节对象的情况下设置了编码关键字参数。

我们只能在传递有效字节对象时设置编码。

print(str(b'abc', encoding='utf-8')) # 👉️ "abc"

如果需要连接字符串,请使用加法 + 运算符。

print('abc' + str(123))  # 👉️ "abc123"

加法 + 运算符可用于连接字符串。

或者,我们可以使用格式化的字符串文字。

str_1 = 'abc'

num_1 = 123

result = f'{str_1} {num_1}'

print(result)  # 👉️ 'abc 123'

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

确保将表达式用大括号括起来 – {expression}

“TypeError: decoding str is not supported”错误消息意味着我们正在尝试以某种方式解码 str。

由于字符串已经从字节对象中解码出来,因此我们需要删除任何试图解码它的代码。

这是一个将字符串编码为字节并将字节对象解码回字符串的简单示例。

my_bytes = 'hello world'.encode('utf-8')
print(my_bytes)  # 👉️ b'hello world'

my_str = my_bytes.decode('utf-8')
print(my_str)  # 👉️ "hello world"

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

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


总结

当我们尝试多次将对象转换为字符串或在调用 str() 类时设置编码关键字参数而不提供字节对象时,会出现 Python“TypeError: decoding str is not supported”。